在golang中将uint64转换为字符串

Ant*_*ony 41 string type-conversion go strconv

我想打印string一个uint64,但没有组合strconv,我用的是工作方法.

log.Println("The amount is: " + strconv.Itoa((charge.Amount)))
Run Code Online (Sandbox Code Playgroud)

给我:

cannot use charge.Amount (type uint64) as type int in argument to strconv.Itoa

我怎么打印这个string

icz*_*cza 61

strconv.Itoa()期望值的类型int,所以你必须给它:

log.Println("The amount is: " + strconv.Itoa(int(charge.Amount)))
Run Code Online (Sandbox Code Playgroud)

但是要知道如果int是32位(虽然uint64是64),这可能会失去精度,但是签名也是不同的.strconv.FormatUint()会更好,因为它需要一个类型的值uint64:

log.Println("The amount is: " + strconv.FormatUint(charge.Amount, 10))
Run Code Online (Sandbox Code Playgroud)

有关更多选项,请参阅以下答案:Golang:格式化字符串而不打印?

如果你的目的是为了只打印值,则无需将其转换,既不int也没有string,使用的其中之一:

log.Println("The amount is:", charge.Amount)
log.Printf("The amount is: %d\n", charge.Amount)
Run Code Online (Sandbox Code Playgroud)


小智 23

如果你想转换int64string,你可以使用:

strconv.FormatInt(time.Now().Unix(), 10)
Run Code Online (Sandbox Code Playgroud)

要么

strconv.FormatUint
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您确实希望将其保存在字符串中,则可以使用Sprint函数之一.例如:

myString := fmt.Sprintf("%v", charge.Amount)
Run Code Online (Sandbox Code Playgroud)

  • 为什么不只是`fmt.Sprint(charge.Amount)`? (5认同)