1. 程式人生 > 其它 >golang struct 欄位null_Go 語言中提取欄位和方法

golang struct 欄位null_Go 語言中提取欄位和方法

技術標籤:golang struct 欄位null

struct 是一系列包含名稱和型別的欄位。通常就像這樣:

package main
import "fmt"
type Person struct {
    name string
    age int32
}
func main() {
    person := Person{name: "Michał", age: 29}
    fmt.Println(person)  // {Michał 29}
}

(在這篇博文的接下來部分,我將逐步刪除包名、匯入和主函式的定義)

上面的結構體中,每個欄位都有明確的名字。Go 語言也允許不指定欄位名稱。沒有名稱的欄位稱為匿名欄位或者內嵌欄位。型別的名字(如果有包名,不包含這個字首的包名)就作為欄位的名字。因為結構體中要求至少有一個唯一的欄位名,所以我們不能這樣做:

import (
    "net/http"
)
type Request struct{}
type T struct {
    http.Request // field name is "Request"
    Request // field name is "Request"
}

如果編譯,編譯器將丟擲錯誤:

> go install github.com/mlowicki/sandbox
# github.com/mlowicki/sandbox
src/github.com/mlowicki/sandbox/sandbox.go:34: duplicate field Request

帶有匿名的欄位或者方法,可以用一個簡潔的方式訪問到:

type Person struct {
    name string
    age int32
}
func (p Person) IsAdult() bool {
    return p.age >= 18
}
type Employee struct {
    position string
}
func (e Employee) IsManager() bool {
    return e.position == "manager"
}
type Record struct {
    Person
    Employee
}
...
record := Record{}
record.name = "Michał"
record.age = 29
record.position = "software engineer"
fmt.Println(record) // {{Michał 29} {software engineer}}
fmt.Println(record.name) // Michał
fmt.Println(record.age) // 29
fmt.Println(record.position) // software engineer
fmt.Println(record.IsAdult()) // true
fmt.Println(record.IsManager()) // false

匿名(嵌入)的欄位和方法被呼叫時會自動向上提升(來找到對應的物件)。

他們的行為跟常規欄位類似,但卻不能用於結構體字面值:

//record := Record{}
record := Record{name: "Michał", age: 29}

它將導致編譯器丟擲錯誤:

// src/github.com/mlowicki/sandbox/sandbox.go:23: unknown Record field ‘name’ in struct literal
// src/github.com/mlowicki/sandbox/sandbox.go:23: unknown Record field ‘age’ in struct literal

可以通過建立一個明確的,完整的,嵌入的結構體來達到我們的目的:

Record{Person{name: "Michał", age: 29}, Employee{position: "Software Engineer"}}

來源:

be1f8b74a1ead81ffc760313b31623a2.png