简体   繁体   中英

Initialize multiple values in a struct using one function

I would like to initialize multiple variables in a struct using the same function like so:

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   
}

however, I can not due to having to use : to initialize variables when creating a struct, is there any way I can do something that is valid yet like the code above?

Using composite literal you can't.

Using tuple assignment you can:

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

Testing it:

p := newtemp(2)
fmt.Println(p)

Output (try it on the Go Playground ):

&{4 6}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM