re3el
re3el

Reputation: 785

How to pass interface of struct type by reference in golang?

I need to pass an interface of a struct type by reference as shown below. Since, I can't use pointers of interface to struct type variables, how should I change the below code to modify te value to 10?.

package main

import (
    "fmt"
)

func another(te *interface{}) {
    *te = check{Val: 10}
}

func some(te *interface{}) {
    *te = check{Val: 20}
    another(te)
}

type check struct {
    Val int
}

func main() {
    a := check{Val: 100}
    p := &a
    fmt.Println(*p)
    some(p)
    fmt.Println(*p)
}

Thanks!

P.S I have read that passing pointers to interfaces is not a very good practice. Kindly let me know what could be a better way to handle it

Upvotes: 10

Views: 17382

Answers (2)

Osman Chowdhury
Osman Chowdhury

Reputation: 351

Something similar to the below should work

func some(te interface{}) {
    switch te.(type) {
    case *check:
        *te.(*check) = check{Val: 20}
    }
}

Upvotes: 1

dave
dave

Reputation: 64657

So you're using an interface, and you need some sort of guarantee that you can set the value of a member of the struct? Sounds like you should make that guarantee part of the interface, so something like:

type Settable interface {
    SetVal(val int)
}

func (c *check) SetVal(val int) {
    c.Val = val
}

func some(te Settable) {
    te.SetVal(20)
}

type check struct {
    Val int
}

func main() {
    a := check{Val: 100}
    p := &a
    some(p)
    fmt.Println(*p)
}

Upvotes: 14

Related Questions