使用一个函数在结构中初始化多个值

ano*_*ose 1 struct go

我想使用相同的函数初始化结构中的多个变量,如下所示:

type temp struct {
    i int
    k int
}

func newtemp(age int) *temp{
    return &temp{
        i, k := initializer(age)
    }
}
func initializer(age int)(int, int){
    return age * 2, age * 3   
}
Run Code Online (Sandbox Code Playgroud)

但是,我不能因为:在创建结构时必须使用初始化变量,有什么方法可以做一些有效的东西,就像上面的代码一样?

icz*_*cza 5

使用复合文字你不能.

使用元组赋值您可以:

func newtemp(age int) *temp{
    t := temp{}
    t.i, t.k = initializer(age)
    return &t
}
Run Code Online (Sandbox Code Playgroud)

测试它:

p := newtemp(2)
fmt.Println(p)
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上试试):

&{4 6}
Run Code Online (Sandbox Code Playgroud)