3 回答

TA貢獻1809條經驗 獲得超8個贊
這似乎做到了:
package main
type toto struct { name string }
func transform (data ...interface{}) {
t := data[0].(*toto)
t.name = "tutu"
}
func main() {
var titi toto
transform(&titi)
println(titi.name == "tutu")
}

TA貢獻1796條經驗 獲得超10個贊
聽起來你想要一個指針。
在您的示例中,您使用了 一個數組,這有特殊原因嗎?一般來說,你應該在 Go 中顯式說明你的類型,特別是因為你正在處理一個簡單的結構。interface{}
package main
import (
"log"
)
type toto struct {
Name string
}
// to help with printing
func (t *toto) String() string {
return t.Name
}
// transform takes an array of pointers to the toto struct
func transform(totos ...*toto) {
log.Printf("totos before: %v", totos)
// unsafe array access!
totos[0].Name = "tutu"
log.Printf("totos after: %v", totos)
}
func main() {
// variables in Go are usually defined like this
titi := toto{}
transform(&titi)
}聽起來你想要一個指針。
在您的示例中,您使用了 一個數組,這有特殊原因嗎?一般來說,你應該在 Go 中顯式說明你的類型,特別是因為你正在處理一個簡單的結構。interface{}
package main
import (
"log"
)
type toto struct {
Name string
}
// to help with printing
func (t *toto) String() string {
return t.Name
}
// transform takes an array of pointers to the toto struct
func transform(totos ...*toto) {
log.Printf("totos before: %v", totos)
// unsafe array access!
totos[0].Name = "tutu"
log.Printf("totos after: %v", totos)
}
func main() {
// variables in Go are usually defined like this
titi := toto{}
transform(&titi)
}

TA貢獻1886條經驗 獲得超2個贊
在 Go 中,在函數中作為參數傳遞的變量實際上是變量的副本,而不是實際變量本身。如果要修改傳遞的變量,需要將其作為指針傳入。
就個人而言,每當我創建一個接受結構的函數時,我都會將該函數設置為接受指向該結構的實例的指針。這具有更高的內存效率的好處(因為我的程序不必在每次調用函數時都創建變量的副本),并且它允許我修改我傳遞的結構的實例。
這就是我的做法:
package main
import (
"github.com/sirupsen/logrus"
)
type toto struct {
name string
}
func transform (t *toto) {
logrus.Info("t before: ", t)
// since t is a pointer to a toto struct,
// I can directly assign "tutu" to the "name" field
// using the "dot" operator
t.name = "tutu"
logrus.Info("t after: ", t)
}
func main() {
// init a pointer to a toto instance
titi := &toto{}
logrus.Info("titi before: ", titi) // -> empty
// this works because transform() accepts a pointer
// to a toto struct and and titi is a pointer to a toto instance
transform(titi)
logrus.Info("titi after (as a pointer): ", titi) // -> not empty
logrus.Info("titi after (as a value): ", *titi) // -> also not empty
}
- 3 回答
- 0 關注
- 89 瀏覽
添加回答
舉報