英文:
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
}
英文:
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
}
答案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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论