猿问

无法将 time.Now() 转换为字符串

我有这个结构:


// Nearby whatever

type Nearby struct {

    id          int    `json:"id,omitempty"`

    me          int    `json:"me,omitempty"`

    you         int    `json:"you,omitempty"`

    contactTime string `json:"contactTime,omitempty"`

}

然后我称之为:


strconv.Itoa(time.Now())

像这样:


s1 := Nearby{id: 1, me: 1, you: 2, contactTime: strconv.Itoa(time.Now())}

但它说:


> cannot use time.Now() (type time.Time) as type int in argument to

> strconv.Itoa

有谁知道那是什么?我想在这里将一个 int 转换为一个字符串。


Smart猫小萌
浏览 163回答 1
1回答

撒科打诨

有谁知道那是什么?我想在这里将一个 int 转换为一个字符串。时间类型不等同于 int。如果您需要的是字符串表示,typeTime有一个String()方法。下面的示例代码(也可作为可运行的 Go Playground代码段提供):package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")// Nearby whatevertype Nearby struct {&nbsp; &nbsp; id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int&nbsp; &nbsp; me&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int&nbsp; &nbsp; you&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int&nbsp; &nbsp; contactTime string}func main() {&nbsp; &nbsp; s1 := Nearby{&nbsp; &nbsp; &nbsp; &nbsp; id:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1,&nbsp; &nbsp; &nbsp; &nbsp; me:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1,&nbsp; &nbsp; &nbsp; &nbsp; you:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2,&nbsp; &nbsp; &nbsp; &nbsp; contactTime: time.Now().String(), // <-- type Time has a String() method&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("%+v", s1)}希望这可以帮助。干杯,
随时随地看视频慕课网APP

相关分类

Go
我要回答