使用空接口更改函数中的arg

问题描述

我正在使用Golang,并且有一个问题:

我可以编写以下函数

func newprint(a interface{}){
    switch a.(type){
    case int:
        fmt.println("this is integer")
    case string:
        fmt.println("this is string")
    case float:
        fmt.println("this is float")
}
}

我想使用一个使用空接口的函数,并根据其类型更改arg。 例如:

如果arg的类型为int i,则要向其中添加2个单元
如果arg的类型为float i,则要为其添加5个单位,并且
如果arg的类型是字符串,则只需打印

解决方法

要修改变量,请将指向变量的指针传递给函数:

func newChange(a interface{}) {
    switch a := a.(type) {
    case *int:
        *a += 2
    case *float64:
        *a += 5.0
    }
}

这样称呼:

a := 1
newChange(&a)

Run this program on the GoLang PlayGround