พื้นฐาน Go

Go Variables and Constants: var, := and const

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

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • 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.

ประเด็นสำคัญ

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

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
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)
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
Go 2009 15 100
gopher 1.21

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Data Types →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด