简体   繁体   中英

Golang method param interface{}

code:

type String struct {
    Result string
}

func main() {
    result := &String{Result:"value"}
    //var test string= "value"
    //result := &test

    testDataBase(result)
    fmt.Print(result.Result) //expect:"34",but:"value"
}

func testDataBase(str interface{}) {
    strV,ok := str.(String)
    if ok {
        strV.Result="34"
    }
}

so,how can I get the result :34 ?

Use strV, ok := str.(*String) ,
Like this working sample code:

package main

import "fmt"

type String struct{ Result string }

func main() {
    result := &String{Result: "value"}    
    testDataBase(result)
    fmt.Println(result.Result)
}

func testDataBase(str interface{}) {
    strV, ok := str.(*String)
    if !ok {
        panic("error")
    }
    strV.Result = "34"
}

output:

34

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