Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何在Go中分离数组(类型结构)?_String_Go_Types - Fatal编程技术网

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

String 如何在Go中分离数组(类型结构)?,string,go,types,String,Go,Types,我刚刚创建此代码是为了试验类型,稍后我将解释这些问题 我的代码: package main import ( "fmt" "math/rand" "time" ) type Games struct { game string creator string } func main() { videogames := []Games{ {"inFamous", "Sucker Punch Games"},

我刚刚创建此代码是为了试验
类型
,稍后我将解释这些问题

我的代码:

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
现在我要做的是分离数组,这样结果

{inFamous,Sucker Punch Games}
Game = inFamous
Publisher = Sucker Punch Games

此外,我还需要删除开始和结束括号。

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

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

查看

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

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

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

相反,请使用
fmt.Printf()
。这应该满足您的需要:

fmt.Printf("Game = %s\nPublisher = %s", videogames[i].game, videogames[i].creator)
fmt.Print()
不允许您指定格式,但将使用类型默认格式

相反,请使用
fmt.Printf()
。这应该满足您的需要:

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