简体   繁体   English

使用结构传递多个值 GO

[英]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.您可以在 struct Pack 上创建一个方法,该方法将初始化值。 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游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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