3 回答

TA貢獻(xiàn)1809條經(jīng)驗 獲得超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貢獻(xiàn)1796條經(jīng)驗 獲得超10個贊
聽起來你想要一個指針。
在您的示例中,您使用了 一個數(shù)組,這有特殊原因嗎?一般來說,你應(yīng)該在 Go 中顯式說明你的類型,特別是因為你正在處理一個簡單的結(jié)構(gòu)。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)
}聽起來你想要一個指針。
在您的示例中,您使用了 一個數(shù)組,這有特殊原因嗎?一般來說,你應(yīng)該在 Go 中顯式說明你的類型,特別是因為你正在處理一個簡單的結(jié)構(gòu)。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貢獻(xiàn)1886條經(jīng)驗 獲得超2個贊
在 Go 中,在函數(shù)中作為參數(shù)傳遞的變量實際上是變量的副本,而不是實際變量本身。如果要修改傳遞的變量,需要將其作為指針傳入。
就個人而言,每當(dāng)我創(chuàng)建一個接受結(jié)構(gòu)的函數(shù)時,我都會將該函數(shù)設(shè)置為接受指向該結(jié)構(gòu)的實例的指針。這具有更高的內(nèi)存效率的好處(因為我的程序不必在每次調(diào)用函數(shù)時都創(chuàng)建變量的副本),并且它允許我修改我傳遞的結(jié)構(gòu)的實例。
這就是我的做法:
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 關(guān)注
- 87 瀏覽
添加回答
舉報