英文:
How to separate arrays (type structs) in Go?
问题
我刚刚创建了这段代码来尝试使用type
,稍后我会解释问题。
我的代码:
package main
import (
"fmt"
"math/rand"
"time"
)
type Games struct {
game string
creator string
}
func main() {
videogames := []Games{
{"inFamous", "Sucker Punch Games"},
{"Halo", "343 Games"},
{"JustCause", "Eidos"},
}
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Intn(len(videogames))
fmt.Print(videogames[i])
}
如果我运行这段代码,结果将是:
{inFamous,Sucker Punch Games}
现在我想要做的是将数组分开,使结果变为:
游戏 = inFamous
发行商 = Sucker Punch Games
另外,我需要去掉开头和结尾的大括号。
英文:
I just created this code to experiment with type
, i will explain the problems later.
My Code:
package main
import (
"fmt"
"math/rand"
"time"
)
type Games struct {
game string
creator string
}
func main() {
videogames := []Games{
{"inFamous", "Sucker Punch Games"},
{"Halo", "343 Games"},
{"JustCause", "Eidos"},
}
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Intn(len(videogames))
fmt.Print(videogames[i])
}
If I run this the result will be,
{inFamous,Sucker Punch Games}
Now what i want to do is separate the arrays so that the result will be,
Game = inFamous
Publisher = Sucker Punch Games
Also i need to remove the opening and closing brackets.
答案1
得分: 3
你需要一个字符串方法来定义对象的打印方式:
func (g Games) String() string {
return fmt.Sprintf("Game = %v, Creator = %v", g.game, g.creator)
}
请查看Go之旅。
英文:
You need a stringer method to define how your object will be printed:
func (g Games) String() string {
return fmt.Sprintf("Game = %v, Creator = %v", g.game, g.creator)
}
Check out the Tour of Go
答案2
得分: 1
fmt.Print()
不允许你指定格式,而是使用类型的默认格式。
相反,使用fmt.Printf()
。这应该可以满足你的需求:
fmt.Printf("Game = %s\nPublisher = %s", videogames[i].game, videogames[i].creator)
英文:
fmt.Print()
does not allow you to specify the format, but will use the type default format.
Instead, use fmt.Printf()
. This should do what you need:
fmt.Printf("Game = %s\nPublisher = %s", videogames[i].game, videogames[i].creator)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论