如何在Go中分离数组(类型为结构体)?

huangapple go评论102阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2017年7月16日 19:14:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/45127907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定