package main
import (
"fmt"
)
type test struct {
a int
b string
}
func newTest1(a int, b string) *test {
t := new(test)
t.a = a
t.b = b
return t
}
func newTest2(a int, b string) *test {
return &test{a, b}
}
type testConstruct func(*test)
func constructA(a int) testConstruct {
return func(t *test) { t.a = a }
}
func constructB(b string) testConstruct {
return func(t *test) { t.b = b }
}
func newTest3(constructs ...testConstruct) *test {
t := new(test)
for _, construct := range constructs {
construct(t)
}
return t
}
func main() {
t1 := &test{b: "2", a: 1}
// t1 := &test{1}// too few values in test literal
t2 := newTest1(2, "3")
t3 := newTest2(3, "4")
t4 := newTest3(constructA(4), constructB("5"))
fmt.Println(t1, t2, t3, t4)
}
记录一下4种构造函数:
- 直接使用&struct{},大括号里可以带上初始化的值。如果写了属性,那么初始化就不需要按照顺序了;初始化的话一定要填上所有的值
- 使用构造函数new构造一个变量
- 使用构造函数&struct构造一个变量,&struct和new是相同的
- 每个属性设置一个赋值函数,并且返回相同的函数指针,参数是这个结构体。在初始化的时候遍历所有的函数指针对这个结构体进行赋值
本文介绍了Go语言中四种构造函数的使用方式:1) 直接使用`&struct{}`进行初始化;2) 使用`new`函数创建变量;3) 使用`&struct`构造变量,与`new`相同;4) 通过为每个属性设置赋值函数进行初始化。在初始化过程中,可以通过这些函数指针对结构体的属性进行赋值。

7022

被折叠的 条评论
为什么被折叠?



