How to concatenate strings and ints natively?

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

How to concatenate strings and ints natively?

问题

我目前找到的在Go语言中将字符串与整数连接的最短(最简洁)方法如下:

"blahblah" + strconv.Itoa(42) + "something"

(导入strconv包)

由于Go语言的一个原则是保持简单,我对于需要导入一个包来完成这个操作感到惊讶。

因此,我的问题是:是否有任何本地(更简洁)的方法来实现这个操作?


显然,我尝试了以下语法,但它甚至无法编译通过:

"blahblah" + 42 + "something"

我还尝试了下面这个语法,实际上它是对值进行了类型转换,这不是我想要的(它将值转换为相应的Unicode字符,对于值42,它将是*):

"blahblah" + string(42) + "something"
英文:

The shortest (cleanest) way I have found so far to concatenate strings with ints in Go is the following:

"blahblah" + strconv.Itoa(42) + "something"

(importing package strconv)

Since one motto of the Go language is to be simple, I was surprised to have to import a package to do this.

Hence, my question: is there any native (thus cleaner) way of doing this?


Obviously, I tried the following syntax, which does not even compile:

"blahblah" + 42 + "something"

I also tried that one, which is in fact a cast of the value, which is not what I want (it converts the value to the corresponding unicode character, which would be * for the value 42):

"blahblah" + string(42) + "something"

答案1

得分: 1

这将起到作用(尽管它使用了反射):

str := fmt.Sprintf("blah %d blah", 42)
英文:

This'll do the trick (it uses reflection though):

str := fmt.Sprintf("blah %d blah", 42)

答案2

得分: -1

你可以使用不同的打印命令来实现你想要的效果。虽然不是一行代码,但它可以工作。

package main

import "fmt"

func main() {
    fmt.Print("blahblah")
    fmt.Print(42)
    fmt.Print("something")
}

Playground

英文:

You can use different print commands to do what you want. It's not a one liner, but it works.

package main

import "fmt"

func main() {
	fmt.Print("blahblah")
	fmt.Print(42)
	fmt.Print("something")
}

Playground

huangapple
  • 本文由 发表于 2014年12月30日 07:25:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/27697493.html
匿名

发表评论

匿名网友

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

确定