2 回答

TA贡献1828条经验 获得超3个赞
一种方法是更改房间函数以返回Person结构或结构的属性Person。
在此处查看实时代码:The Go Playground
例如,
func northRoom() *Person{
fmt.Println("You find yourself in a room with a door on the wall behind you")
fmt.Println("You see several statues of people standing around the room")
return &Person{"Joe", 58}
}
switch现在,您的语句中的函数调用可以期望Person返回一个结构。
var p *Person
switch r1.Intn(4){
case 0:
p = westRoom()
case 1:
p = eastRoom()
case 2:
p = northRoom()
case 3:
p = southRoom()
default:
p = lostRoom()
}
avatar(p)
appearance(p)
请注意,您需要更改avatar()和appearance()函数的签名以接受*Person参数。

TA贡献1818条经验 获得超8个赞
为什么不让您的房间功能返回 a Person?例子:
func main() {
// These two lines are designed to reset the random Seed every time the program is run
// Unless the randomizer is seeded, Golang 1.6 is pseudo-random,
// always defaulting to Seed(1)
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
var p Person
switch r1.Intn(4) {
case 0:
p = westRoom()
case 1:
p = eastRoom()
case 2:
p = northRoom()
case 3:
p = southRoom()
default:
lostRoom()
}
p.printAvatar()
p.printAppeareance()
}
func westRoom() Person {
fmt.Println("You find yourself in a room with three walls, and a door behind you.")
fmt.Println("The opposite wall is a window, overlooking the sea")
return Person{
Name: "Bill",
Age: 25,
}
}
https://play.golang.org/p/9_PuPsRdXg
- 2 回答
- 0 关注
- 263 浏览
添加回答
举报