gpt4 book ai didi

string - 如何在 Golang 中将映射解压缩为字符串格式的关键字参数?

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:27 26 4
gpt4 key购买 nike

在 Python 中,要用字典格式化字符串,可以简单地这样做:

geopoint = {
'latitude': 41.123,
'longitude':71.091
}

print('{latitude} {longitude}'.format(**geopoint))

输出将为 41.123 71.091。如何在 Go 中实现字符串格式化的相同关键字解包?

编辑:抱歉,如果这个问题不清楚,但我想做的是,就像在 Python 中一样,为格式字符串中的值提供键。

最佳答案

Carpetsmoker 的想法,但使用文本/模板的解决方案看起来像这样。

https://play.golang.org/p/s2lPgA-Xa6C

package main

import (
"os"
"text/template"
)

func main() {
geopoint := map[string]float64{
"latitude": 41.123,
"longitude": 71.091,
}
template.Must(template.New("").Parse(`{{ .latitude }} {{ .longitude }}`)).Execute(os.Stdout, geopoint)
}

关于string - 如何在 Golang 中将映射解压缩为字符串格式的关键字参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49246200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com