3

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?

4
  • What about returning the struct directly from the function? Commented Jun 24, 2016 at 6:30
  • you can have the initizalizer func take references: func initializer(i1 *int, i2 *int) { *i1=1; *i2=2} and pass t:= &temp{}; initializer(&t.i, &t.k) into it Commented Jun 24, 2016 at 6:33
  • but it looks like a hack to me, can you maybe give more detail on why you would want to have this initializer function separate from the newTemp ? Commented Jun 24, 2016 at 6:34
  • "I would like to <do something the language spec does not allow>." does not make a very good question. Commented Jun 24, 2016 at 6:43

1 Answer 1

8

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}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.