i := 123
s := string(i)
Run Code Online (Sandbox Code Playgroud)
s是'E',但我想要的是"123"
请告诉我如何获得"123".
在Java中,我可以这样做:
String s = "ab" + "c" // s is "abc"
Run Code Online (Sandbox Code Playgroud)
我怎么能concat
在Go中使用两个字符串?
我想将字符串分配给bytes数组:
var arr [20]byte
str := "abc"
for k, v := range []byte(str) {
arr[k] = byte(v)
}
Run Code Online (Sandbox Code Playgroud)
有另一种方法吗?
我试图从返回的字符串转换flag.Arg(n)
成int
.在Go中这样做的惯用方法是什么?
我需要解码一个带有浮点数的JSON字符串,如:
{"name":"Galaxy Nexus", "price":"3460.00"}
Run Code Online (Sandbox Code Playgroud)
我使用下面的Golang代码:
package main
import (
"encoding/json"
"fmt"
)
type Product struct {
Name string
Price float64
}
func main() {
s := `{"name":"Galaxy Nexus", "price":"3460.00"}`
var pro Product
err := json.Unmarshal([]byte(s), &pro)
if err == nil {
fmt.Printf("%+v\n", pro)
} else {
fmt.Println(err)
fmt.Printf("%+v\n", pro)
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,得到结果:
json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}
Run Code Online (Sandbox Code Playgroud)
我想知道如何使用convert类型解码JSON字符串.
http://golang.org/pkg/strconv/
http://play.golang.org/p/4VNRgW8WoB
如何将浮点数转换为字符串格式?这是谷歌游乐场,但没有得到预期的输出.(2e + 07)我想得到"21312421.213123"
package main
import "fmt"
import "strconv"
func floattostr(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'g', 1, 64)
}
func main() {
fmt.Println(floattostr(21312421.213123))
// what I expect is "21312421.213123" in string format
}
Run Code Online (Sandbox Code Playgroud)
请帮我从浮点数中取出字符串.谢谢
我想一个转换bool
称为isExist
一个string
(true
或false
使用)string(isExist)
,但它不工作.在Go中这样做的惯用方法是什么?
是否存在将bool转换为整数的内置方法,反之亦然?我尝试过普通的转换,但由于它们使用不同的底层类型,转换是不可能的经典方式.我已经倾注了一些规范,但我还没有找到答案.
我需要在Golang中转换int32
为string
.是否有可能转换int32
为string
Golang而不转换为int
或int64
首先?
Itoa
需要一个int
.FormatInt
需要一个int64
.
使用Go我试图找到将浮点数格式化为字符串的"最佳"方法.我找了一些例子但是找不到任何具体回答我的问题的东西.我想要做的就是使用"最佳"方法将浮点数格式化为字符串.小数位数可能会有所不同,但是已知(例如,2或4或零).我想要实现的一个例子如下.根据下面的例子,我应该使用fmt.Sprintf()或strconv.FormatFloat()还是其他什么?并且,每个的正常用法和每个之间的差异是什么?
我也不明白在下面使用32或64当前有32的重要性:
strconv.FormatFloat(float64(fResult), 'f', 2, 32)
Run Code Online (Sandbox Code Playgroud)
例:
package main
import (
"fmt"
"strconv"
)
func main() {
var (
fAmt1 float32 = 999.99
fAmt2 float32 = 222.22
)
var fResult float32 = float32(int32(fAmt1*100) + int32(fAmt2*100)) / 100
var sResult1 string = fmt.Sprintf("%.2f", fResult)
println("Sprintf value = " + sResult1)
var sResult2 string = strconv.FormatFloat(float64(fResult), 'f', 2, 32)
println("FormatFloat value = " + sResult2)
}
Run Code Online (Sandbox Code Playgroud) http://play.golang.org/p/BoZkHC8_uA
我想将uint8转换为字符串,但无法弄清楚如何.
package main
import "fmt"
import "strconv"
func main() {
str := "Hello"
fmt.Println(str[1]) // 101
fmt.Println(strconv.Itoa(str[1]))
}
Run Code Online (Sandbox Code Playgroud)
这给了我 prog.go:11: cannot use str[1] (type uint8) as type int in function argument
[process exited with non-zero status]
任何的想法?