Variables & Types
Declaring variables in C and Go
Introduction
In this lesson, you'll learn about variables & types in Go. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with declaring variables in c and go.
Go has its own approach to declaring variables in c and go, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
package main
import "fmt"
func main() {
var age int = 30
var score float32 = 9.5
pi := 3.14159 // float64 inferred
letter := 'A' // rune (int32)
const Max = 100
active := true // real bool type
fmt.Printf("age=%d pi=%.5f\n", age, pi)
}Comparing to C
Here's how you might have written similar code in C:
#include <stdio.h>
int main() {
int age = 30;
float score = 9.5f;
double pi = 3.14159;
char letter = 'A';
const int MAX = 100;
/* C-style bool */
int active = 1;
printf("age=%d pi=%.5f\n", age, pi);
return 0;
}You may be used to different syntax or behavior.
Go has a real bool type; C uses int (0/1)
You may be used to different syntax or behavior.
Go's := for short declaration with inference; C requires explicit type
You may be used to different syntax or behavior.
Go's rune is Unicode code point; C's char is a byte
You may be used to different syntax or behavior.
Go has no unsigned/long/short keywords — uses int8/int32/int64/uint64 etc.
Step-by-Step Breakdown
1. Short Declaration
Go's := declares and assigns in one step with type inference, replacing C's type + assignment pattern.
int x = 42;x := 42 // int inferred2. Type Names
Go's integer types are explicit: int8, int16, int32, int64 (and unsigned variants). int is platform-sized like C's int.
int x; long y; unsigned int z;var x int; var y int64; var z uint3. Constants
Go constants use the const keyword and support iota for auto-incrementing enum-like values.
const (
StatusOK = iota // 0
StatusError // 1
StatusNotFound // 2
)Common Mistakes
When coming from C, developers often make these mistakes:
- Go has a real bool type; C uses int (0/1)
- Go's := for short declaration with inference; C requires explicit type
- Go's rune is Unicode code point; C's char is a byte
Key Takeaways
- Go has bool (true/false); C uses int
- := replaces C's type declaration + assignment
- Go integer types: int, int64, uint32, etc.
- Go const + iota replaces C's enum/define patterns