dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

Go: Type declarations #55

Open dushaoshuai opened 1 year ago

dushaoshuai commented 1 year ago

Go 中,类型声明(type declarations)有两种形式:别名声明(alias declarations)和类型定义(type definitions)。

别名声明

新类型只是一个别名,他和给定的类型完全相同。在下面的例子中,myFloat64 完全等同于 float64myString 完全等同于 stringstringList 完全等同于 []myString

type myFloat64 = float64

type (
    myString   = string
    stringList = []myString
)

在下面的例子中,stringBuilder 可以像 strings.Builder 一样使用:

type stringBuilder = strings.Builder

func Example_alias_declarations() {
    var b stringBuilder
    for i := 3; i >= 1; i-- {
        fmt.Fprintf(&b, "%d...", i)
    }
    b.WriteString("ignition")
    fmt.Println(b.String())

    // Output:
    // 3...2...1...ignition
}

类型定义

类型定义定义新类型,新类型不同于包括给定类型在内的任何其他类型,新类型称为 defined type。在下面的例子中,myFloat64float64 是不同的类型,myStringstring 是不同的类型,stringList[]myString 是不同的类型:

type myFloat64 float64

type (
    myString   string
    stringList []myString
)

var f1 float64 = 23

var f2 myFloat64 = f1 // cannot use f1 (variable of type float64) as myFloat64 value in variable declaration

新类型可以定义方法:

type os struct{}

func (os) halt()      {}
func (os) poweroff()  {}
func (os) reboot()    {}
func (os) suspend()   {}
func (os) hibernate() {}

func Example_new_defined_type_with_methods() {
    var linux os
    linux.reboot()
    linux.poweroff()

    // Output:
}

新类型不继承给定类型的任何方法,但是接口类型和复合类型的元素的方法保持不变:

type table string

func (t table) tableName() string {
    return string(t)
}

type model table

func Example_no_inherit() {
    var t table = "user"
    fmt.Println(t.tableName())

    var m model = "error"
    fmt.Println(m.tableName()) // m.tableName undefined (type model has no field or method tableName)

    // Output:
}

类型定义可以定义泛型类型(generic type):

type list[T any] struct {
    next  *list[T]
    value T
}

func (l *list[T]) Len() int { return 0 }

See also

Type declarations