Golang方法参数接口{}

donsonzhang:

码:

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"
    }
}

所以,我怎么得到结果:34?

用户6169399:

使用strV, ok := str.(*String)
就像这样的工作示例代码:

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"
}

输出:

34

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章