我正在尝试通过使用由该结构实现的接口的方法来设置具体结构中属性的值。该结构也由另一个结构组成。
在下面的示例中,userId值保持为“ aaaa”,并且不会更新为“ userid1”。
如何通过方法接口作为参数并将struct作为参数来更新struct的值?
func main() {
user:=User{}
mw:=SomeMiddleware{}
user.UserId="aaaa"
mw.Process(user)
fmt.Println("UserId: " + user.UserId)
}
type IUser interface {
SetUserId(string)
}
type SomeMiddleware struct {
}
func(m SomeMiddleware) Process(user IUser){
user.SetUserId("userid1")
}
type User struct {
UserInfo
}
type UserInfo struct {
UserId string
}
func(ui UserInfo) SetUserId(userId string) {
ui.UserId=userId
}
答案 0 :(得分:1)
您可以使用类似这样的指针
package main
import (
"fmt"
)
func main() {
user := User{}
mw := SomeMiddleware{}
user.UserId = "aaaa"
mw.Process(&user) // Send reference to user here (&user)
fmt.Println("UserId: " + user.UserId)
}
type IUser interface {
SetUserId(string)
}
type SomeMiddleware struct {
}
func (m *SomeMiddleware) Process(user IUser) { // Pointer receiver (m *SomeMiddleware)
user.SetUserId("userid1")
}
type User struct {
UserInfo
}
type UserInfo struct {
UserId string
}
func (ui *UserInfo) SetUserId(userId string) { // Pointer receiver (ui *UserInfo)
ui.UserId = userId
}