In Go, variables are declared using the var keyword, const keyword, or the short declaration syntax :=. Variables can be declared at package level or within a function.
Trong Go, biến được khai báo bằng từ khóa var, const, hoặc bằng cú pháp khai báo ngắn :=. Có thể khai báo biến ở cấp độ gói (package-level) hoặc trong hàm (function-level).
1package main23import "fmt"45func main() {6 // Long declaration with var7 var x int = 58 var y int9 y = 101011 // Short declaration (only inside functions)12 z := 151314 // Multiple declarations15 var a, b, c int = 1, 2, 316 d, e := 4, 51718 fmt.Println(x, y, z, a, b, c, d, e)19}The short syntax := only works inside functions and automatically infers the type from the right-hand value. If no value is assigned, the variable gets a zero value (0 for numbers, "" for strings, false for bool, nil for pointers).
Cú pháp ngắn := chỉ hoạt động bên trong hàm và tự động suy luận kiểu dữ liệu dựa trên giá trị ở phía phải. Nếu không gán giá trị, biến sẽ có giá trị zero (0 cho number, "" cho string, false cho bool, nil cho pointer).
Constants are declared using the const keyword and their value cannot change after initialization. Constants can be typed (with explicit type annotation) or untyped (letting the compiler infer the type).
Hằng số được khai báo bằng từ khóa const và giá trị không thể thay đổi sau khi khởi tạo. Hằng số có thể được viết dưới dạng typed (có chú thích kiểu) hoặc untyped (để trình biên dịch suy luận kiểu).
1package main23import "fmt"45const (6 Monday = iota // 07 Tuesday // 18 Wednesday // 29 Thursday // 310 Friday // 411 Saturday // 512 Sunday // 6iota is a special identifier in const blocks. It starts at 0 and automatically increments by 1 for each line. This is useful for creating enumerations.
iota là một định danh đặc biệt trong const blocks. Nó bắt đầu từ 0 và tự động tăng thêm 1 cho mỗi dòng. Điều này hữu ích để tạo enumerations.
Go has many integer types: int8, int16, int32, int64 (signed), uint8, uint16, uint32, uint64 (unsigned), int, uint (architecture-dependent). For most cases, int or uint is sufficient.
Go có nhiều kiểu số nguyên: int8, int16, int32, int64 (signed — có dấu), uint8, uint16, uint32, uint64 (unsigned — không dấu), int, uint (phụ thuộc kiến trúc máy). Hầu hết các trường hợp, int hoặc uint đều đủ.
1package main23import "fmt"45func main() {6 var a int8 = -128 // -128 to 1277 var b uint8 = 255 // 0 to 255 (also called byte)8 var c int = 42 // Architecture-dependent size9 var d int64 = 92233720368547758071011 fmt.Println(a, b, c, d)12}Go has float32 and float64 (64-bit is default). float64 is recommended to avoid precision loss.
Go có float32 và float64 (64-bit là mặc định). float64 được khuyến nghị để tránh mất độ chính xác.
1package main23import "fmt"45func main() {6 var pi float32 = 3.147 var e float64 = 2.71828182889 fmt.Println(pi, e)10}Strings in Go are immutable and UTF-8 encoded. Strings are wrapped in double quotes. For raw strings (allowing newlines and special characters without escaping), use backticks.
Chuỗi trong Go là bất biến (immutable) và mã hóa UTF-8. Chuỗi được bao bọc bằng dấu ngoặc kép. Để tạo raw string (cho phép xuống dòng và ký tự đặc biệt mà không cần escape), dùng backticks.
1package main23import "fmt"45func main() {6 var name string = "Go"7 greeting := "Hello, " + name89 // Raw string with backticks10 message := `Line 111Line 212Special chars: 13 doesn't escape`1415 fmt.Println(greeting)16 fmt.Println(message)17 fmt.Println(len(greeting)) // length in bytes (5+2=7)18}When a variable is declared but not assigned, it receives a zero value — a default value depending on the data type.
Khi biến được khai báo nhưng không gán giá trị, nó sẽ nhận zero value — một giá trị mặc định phụ thuộc vào kiểu dữ liệu.
1package main23import "fmt"45func main() {6 var i int7 var f float648 var s string9 var b bool10 var p *int1112 fmt.Println(i) // 013 fmt.Println(f) // 014 fmt.Println(s) // "" (empty string)15 fmt.Println(b) // false16 fmt.Println(p) // <nil>17}Go does not automatically convert types. Conversions must be explicit: T(x) converts x to type T. This helps prevent subtle errors.
Go không tự động chuyển đổi kiểu dữ liệu. Chuyển đổi phải rõ ràng: T(x) chuyển đổi x sang kiểu T. Điều này giúp tránh các lỗi tinh tế.
1package main23import "fmt"45func main() {6 var i int = 427 var f float64 = float64(i)8 var u uint = uint(i)910 fmt.Println(f) // 4211 fmt.Println(u) // 421213 // String conversions use strconv package14 s := fmt.Sprintf("%d", i) // Convert int to string15 fmt.Println(s) // "42"16}When using := or var x = value without a type annotation, Go infers the type from the right-hand value. If the value is 42, x becomes int. If 3.14, x becomes float64.
Khi dùng := hoặc var x = value mà không chỉ định kiểu, Go sẽ suy luận kiểu dữ liệu dựa trên giá trị bên phải. Nếu giá trị là 42, x sẽ có kiểu int. Nếu là 3.14, x sẽ có kiểu float64.
1package main23import "fmt"45func main() {6 x := 42 // int7 y := 3.14 // float648 z := "hello" // string9 w := true // bool1011 fmt.Printf("%T12", x) // int13 fmt.Printf("%T14", y) // float6415 fmt.Printf("%T16", z) // string17 fmt.Printf("%T18", w) // bool19}Key Takeaways
Điểm Chính
- Variables declared without assignment receive zero valuesBiến được khai báo mà không gán giá trị sẽ nhận zero value
- Constants are immutable and can be typed or untypedHằng số là bất biến và có thể typed hoặc untyped
- Type conversion in Go is explicit using T(x) syntaxChuyển đổi kiểu trong Go là rõ ràng sử dụng cú pháp T(x)
- iota in const blocks creates auto-incrementing values for enumerationsiota trong const blocks tạo giá trị tự động tăng cho enumerations
Practice
Test your understanding of this chapter
What is the zero value for an integer variable that is declared but not assigned?
Zero value của biến kiểu integer được khai báo nhưng không gán là gì?
Go automatically converts between different numeric types like TypeScript does.
Go tự động chuyển đổi giữa các kiểu số khác nhau như TypeScript làm.
Complete the iota enumeration in a const block
Hoàn thành enumeration iota trong const block
const ( Red = Green Blue )
Which syntax is used for the short variable declaration in Go?
Cú pháp nào được dùng cho khai báo biến ngắn trong Go?
In Go, strings are mutable and encoded in UTF-8.
Trong Go, chuỗi là biến và mã hóa UTF-8.