将值通过引用传递给持有者对象

huangapple go评论79阅读模式
英文:

Pass value by reference to the holder object

问题

以下是代码的翻译:

// 将Holder对象的类型指定为`interface`
type Holder struct {
	Body interface{}
}

// 值对象
type Value struct {
	Input  int
	Result int
}

func main() {
	value := Value{Input: 5}
	holder := Holder{Body: value}

	fmt.Println(value) // {5 0}
	modify(holder)
	fmt.Println(value) // {5 0} 应该显示为 {5 10}
}

func modify(holder Holder) {
	var value Value = holder.Body.(Value)
	value.Result = 2 * value.Input
}

Go Playground

英文:

Following code has Holder specified as of interface type.

What changes can be done to the Holder object so it receives any kind with reference type, so if any changes to the value object, it gets reflected on the main.

type Holder struct {
	Body interface{}
}

type Value struct {
	Input int
	Result int
}

func main() {
	value := Value{Input: 5}
	holder := Holder{Body: value}

	fmt.Println(value) // {5 0}
	modify(holder)
	fmt.Println(value) // {5 0} should display {5 10}
}

func modify(holder Holder) {
	var value Value = holder.Body.(Value)
	value.Result = 2 * value.Input
}

Go Playground

答案1

得分: 1

package main

import "fmt"

type Holder struct {
	Body interface{}
}

type Value struct {
	Input  int
	Result int
}

func main() {
	value := Value{Input: 5}
	holder := Holder{Body: &value}

	fmt.Println(value) // {5 0}
	modify(&holder)
	fmt.Println(value) // {5 0} 应该显示 {5 10}
}

func modify(holder *Holder) {
	var value *Value = holder.Body.(*Value)
	value.Result = 2 * value.Input
}
package main

import "fmt"

type Holder struct {
	Body interface{}
}

type Value struct {
	Input  int
	Result int
}

func main() {
	value := Value{Input: 5}
	holder := Holder{Body: &value}

	fmt.Println(value) // {5 0}
	modify(&holder)
	fmt.Println(value) // {5 0} 应该显示 {5 10}
}

func modify(holder *Holder) {
	var value *Value = holder.Body.(*Value)
	value.Result = 2 * value.Input
}

以上是你提供的代码的翻译。

英文:
package main

import "fmt"

type Holder struct {
	Body interface{}
}

type Value struct {
	Input  int
	Result int
}

func main() {
	value := Value{Input: 5}
	holder := Holder{Body: &value}

	fmt.Println(value) // {5 0}
	modify(&holder)
	fmt.Println(value) // {5 0} should display {5 10}
}

func modify(holder *Holder) {
	var value *Value = holder.Body.(*Value)
	value.Result = 2 * value.Input
}

https://play.golang.org/p/hG8cH4UBPc

huangapple
  • 本文由 发表于 2017年3月10日 06:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/42706630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定