Go cơ bản

Go Variables and Constants: var, := and const

Two ways to declare a variable, what a zero value is, and values that never change.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • var and :=
  • Zero values
  • const
Declaration → result
var year int0, the zero value
score := 10int, inferred
const MaxScore = 100cannot change

Declare, then use

Go has two ways to create a variable. var names the type, and := lets Go work out the type from the value. A variable that is declared without a value gets a zero value such as 0 or an empty string.

year is declared without a value, so it starts at 0 until 2009 is assigned. := can only be used inside a function and can declare several variables at once. A const cannot be changed after it is declared.

Những điểm quan trọng

  1. var names the type; := infers it.
  2. A variable without a value starts at its zero value.
  3. A const cannot change.

Ví dụ Go chạy được

Go
Chạy code →
main.go
package main

import "fmt"

const MaxScore = 100

func main() {
	var language string = "Go"
	var year int // zero value: 0
	score := 10  // short declaration, type inferred
	score += 5
	year = 2009

	name, version := "gopher", 1.21
	fmt.Println(language, year, score, MaxScore)
	fmt.Println(name, version)
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
Go 2009 15 100
gopher 1.21

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Data Types →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách