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种构造函数:
- 直接使用&a