如何解决在函数内部设置类型为empty interface {}的变量的值
这是我正在努力使其正常运行的代码。我想在func getUser中设置user
值,该值采用interface{}
类型的参数。
示例代码:https://play.golang.org/p/Zlhe9VEQhnD
package main
import (
"fmt"
)
type User struct {
name string
}
func getUser(result interface{}) {
result = User{name: "some name"}
fmt.Println(result)
}
func main() {
user := User{}
getUser(&user)
fmt.Println(user)
}
它给出以下结果:
{some name}
{}
我想对功能所做的更改反映在main中
TIA
解决方法
interface参数包含一个指向用户结构的指针。您必须使用类型断言到达该指针,然后将新的用户结构复制到目标结构:
class Repository {
/**
* Generate random number for the bonus number within a particular range set by user
*
* [maxNum]: the number that the user entered which acts as the max range for the random numbers
*/
fun generateBonusRandomNumber(maxNum: Int): Int {
val minNum = 1
// Adding 1[minNum] to the bound makes sure the number the person entered is inclusive
return Random().nextInt(((maxNum - minNum)) + minNum)
}
}