简体   繁体   中英

Using a struct to pass multiple values GO

I have just one question I wrote an example here

package main

import (
  "fmt"
)
type PACK struct {
  d, r int
}

func main() {

  st := &PACK{}
  st.d, st.r = f(12, 32)
}

func f(a, b int) (d int, r int) {
  d = a / b
  r = a ^ b
  return
}

So, the question is - how can i make thing like this

st := &PACK{ f(1,2) }

I want my function return arguments to be a struct initializer!

你不能这样做,这是不可能的。

You can create a method on struct Pack, that will initialize the values. For example:

package main

import "fmt"

type Pack struct {
    d, r int
}

func (p *Pack) init (a, b int) {
    p.d = a / b
    p.r = a ^ b
}

func main() {
    pack := Pack{}   // d and r are initialized to 0 here
    pack.init(10, 4)
    fmt.Println(pack)

}

Result:

{2 14}

goplayground

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