简体   繁体   中英

Setting values of concrete struct by using interface

I am trying to set the value of a property in a concrete struct, with a method that uses and interface implemented by that struct. The struct is also composed by another struct.

With the sample below userId value remains "aaaa" and is not updated to "userid1".

How can I update values of struct through a method interface as parameter and the struct as argument?

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
}

You can use pointers like this,

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM