คู่มือผู้ใช้ Go
ไวยากรณ์พื้นฐาน
การประกาศตัวแปร
Go มีหลายวิธีในการประกาศตัวแปร การประกาศแบบพื้นฐานใช้คำสำคัญ var:
// Declare variable with type
var name string = "Go"
// Type inference declaration
var age = 10
// Batch declaration
var (
firstName string
lastName string
score float64
)
// Short declaration (inside function)
message := "Hello, World!"
ตัวแปรของ Go ต้องถูกใช้หลังจากประกาศ มิฉะนั้นการคอมไพล์จะล้มเหลว หากคุณต้องการประกาศตัวแปรที่ยังไม่ได้ใช้ชั่วคราว คุณสามารถใช้ขีดล่าง _ เพื่อรับค่า:
result, _ := someFunction() // Ignore first return value
การประกาศค่าคงที่
ค่าคงที่ประกาศด้วยคำสำคัญ const และสามารถเป็นอักขระ สตริง ค่าบูลีน หรือตัวเลขได้:
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)
ชนิดข้อมูลพื้นฐาน
ชนิดข้อมูลพื้นฐานของ Go ได้แก่:
- บูลีน: bool (true หรือ false)
- จำนวนเต็ม: int, int8, int16, int32, int64 และชนิดไม่มีเครื่องหมายที่สอดคล้องกัน เช่น uint เป็นต้น
- ทศนิยม: float32, float64
- จำนวนเชิงซ้อน: complex64, complex128
- สตริง: string
การแปลงชนิดข้อมูลต้องทำอย่างชัดเจน:
var i int = 42
var f float64 = float64(i)
var s string = strconv.Itoa(i) // Integer to string
ฟังก์ชัน
การนิยามฟังก์ชัน
ฟังก์ชันของ Go นิยามด้วยคำสำคัญ func:
func greet(name string) string {
return "Hello, " + name
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Named return values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // No need to specify return values
}
พารามิเตอร์แบบผันผวน
ฟังก์ชันสามารถรับจำนวนพารามิเตอร์ที่แปรผันได้:
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Usage
result := sum(1, 2, 3, 4, 5)
ฟังก์ชันปิด (Closures)
Go รองรับฟังก์ชันปิด ซึ่งฟังก์ชันสามารถจับและแก้ไขตัวแปรจากขอบเขตภายนอกได้:
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
// Usage
c := counter()
fmt.Println(c()) // 1
fmt.Println(c()) // 2
การเขียนโปรแกรมแบบทำงานพร้อมกัน
Goroutine
goroutine เป็นหน่วยการทำงานแบบเบาใน Go ที่มีต้นทุนการสร้างต่ำมาก:
// Start goroutine
go func() {
fmt.Println("Hello from goroutine!")
}()
// Goroutine with parameters
go func(msg string) {
fmt.Println(msg)
}("Hello!")
Channel
channel คือกลไกการสื่อสารระหว่าง goroutine:
// Create channel
ch := make(chan string)
// Send data
ch <- "message"
// Receive data
msg := <-ch
// Buffered channel
bufferedCh := make(chan int, 10)
Select
คำสั่ง select ใช้เพื่อรอการดำเนินการบน channel หลายช่องพร้อมกัน:
select {
case msg := <-ch1:
fmt.Println("Received:", msg)
case msg := <-ch2:
fmt.Println("Received:", msg)
case <-time.After(time.Second):
fmt.Println("Timeout")
}
ความปลอดภัยของการทำงานพร้อมกัน
ใช้แพ็กเกจ sync ในการควบคุมการทำงานพร้อมกัน:
var (
mu sync.Mutex
count int
)
func increment() {
mu.Lock()
defer mu.Unlock()
count++
}
การจัดการข้อผิดพลาด
การคืนค่าข้อผิดพลาด
Go ใช้ค่าที่คืนกลับมาในการจัดการข้อผิดพลาด ซึ่งเป็นวิธีที่เป็นแนวปฏิบัติของ Go:
result, err := doSomething()
if err != nil {
return err
}
ข้อผิดพลาดแบบกำหนดเอง
สร้างข้อผิดพลาดแบบกำหนดเองโดยใช้แพ็กเกจ errors:
import "errors"
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
การห่อหุ้มข้อผิดพลาด
Go 1.13 เพิ่มการห่อหุ้มข้อผิดพลาดโดยใช้ fmt.Errorf และคำสั่ง %w:
if err != nil {
return fmt.Errorf("failed to do something: %w", err)
}
อินเทอร์เฟซ
การนิยามอินเทอร์เฟซ
อินเทอร์เฟซของ Go ถูกนำไปใช้งานโดยอัตโนมัติ ไม่ต้องมีการประกาศอย่างชัดเจน:
type Writer interface {
Write([]byte) (int, error)
}
type Reader interface {
Read([]byte) (int, error)
}
// Common composite interface
type ReadWriter interface {
Reader
Writer
}
อินเทอร์เฟซว่าง
อินเทอร์เฟซว่าง interface{} สามารถเก็บค่าของชนิดใดก็ได้:
var i interface{} = 42
var s interface{} = "hello"
var m interface{} = map[string]int{"a": 1}
Go 1.18 เพิ่ม Generics ทำให้สามารถใช้ any แทน interface{} ได้:
var i any = 42
แพ็กเกจและโมดูล
การสร้างโมดูล
ใช้ go mod init เพื่อสร้างโมดูลใหม่:
go mod init github.com/username/project
การจัดการ dependency
เพิ่ม dependency:
go get github.com/pkg/errors
อัปเดต dependency:
go get -u all
ล้าง dependency ที่ไม่ได้ใช้:
go mod tidy
การทดสอบ
การทดสอบหน่วย
Go มีเฟรมเวิร์กการทดสอบในตัวมา ไฟล์ทดสอบจะลงท้ายด้วย _test.go:
import "testing"
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
รันการทดสอบ:
go test ./...
go test -v ./...
go test -cover ./...
การทดสอบเบนช์มาร์ก
ฟังก์ชันเบนช์มาร์กขึ้นต้นด้วย Benchmark:
func BenchmarkHello(b *testing.B) {
for i := 0; i < b.N; i++ {
Hello()
}
}
รันการทดสอบเบนช์มาร์ก:
go test -bench=.
ไลบรารีมาตรฐานที่ใช้บ่อย
fmt - อินพุต/เอาต์พุตแบบมีรูปแบบ
fmt.Println("Hello")
fmt.Printf("Name: %s, Age: %d\n", name, age)
fmt.Sprintf("Result: %d", result)
strings - การจัดการสตริง
strings.Contains(s, "sub")
strings.Split(s, ",")
strings.TrimSpace(s)
strings.ToUpper(s)
net/http - เซิร์ฟเวอร์ HTTP
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, HTTP!")
})
http.ListenAndServe(":8080", nil)
json - การประมวลผล JSON
// Encode
data, _ := json.Marshal(person)
// Decode
var p Person
json.Unmarshal(data, &p)
เครื่องมือที่ใช้บ่อย
gofmt - การจัดรูปแบบโค้ด
gofmt -w main.go # Format and write to file
gofmt -d main.go # Show formatting differences
go vet - การวิเคราะห์แบบคงที่
go vet ./... # Check for code issues
go doc - โปรแกรมดูเอกสาร
go doc fmt.Println # View function documentation
go doc fmt # View package documentation
