【问题标题】:How to separate arrays (type structs) in Go?如何在 Go 中分隔数组(类型结构)?
【发布时间】:2017-12-21 00:38:54
【问题描述】:

我刚刚创建了这段代码来试验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}

现在我要做的是分离数组,以便结果是,

Game = inFamous
Publisher = Sucker Punch Games

我还需要删除左括号和右括号。

【问题讨论】:

    标签: string go types


    【解决方案1】:

    fmt.Print() 不允许您指定格式,但会使用类型默认格式。

    改为使用fmt.Printf()。这应该可以满足您的需要:

    fmt.Printf("Game = %s\nPublisher = %s", videogames[i].game, videogames[i].creator)
    

    【讨论】:

      【解决方案2】:

      您需要一个 stringer 方法来定义您的对象的打印方式:

      func (g Games) String() string {
          return fmt.Sprintf("Game = %v, Creator = %v", g.game, g.creator)
      }
      

      查看Tour of Go

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        相关资源
        最近更新 更多