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 關注
- 249 瀏覽
添加回答
舉報