Golang中Map接口值的字符串插值实现方法

Golang中Map接口值的字符串插值实现方法

anotherValue := "aValue"
Banana := map[string]map[string]interface{}{
		"amap": map[string]interface{}{
			"aKey": "aValue",
			"anotherKey": fmt.Printf("another Value %s", anotherValue)
		},
	} 

我正在尝试在映射(map)内部对一个“值”进行字符串插值操作,具体请参考上面代码中 "anotherKey" 的值。如你所见,我尝试使用 fmt.Printf(),但这并不奏效。对于映射内部的“键/值”对,我该如何解决这个字符串插值/格式化的问题呢? 我尝试了几种不同的方法,但似乎都没有效果。


更多关于Golang中Map接口值的字符串插值实现方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

这是你想要做的吗?https://play.golang.org/p/ryx6AKDjVXS

更多关于Golang中Map接口值的字符串插值实现方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


太棒了,谢谢。我是Go语言的新手。刚刚理解了PrintfSprintf的区别。后者返回一个字符串值,在map中使用非常方便。再次感谢……你真的帮了我大忙。

在Go语言中,fmt.Printf 函数返回的是写入的字节数和错误信息,而不是格式化后的字符串。对于映射值的字符串插值,你应该使用 fmt.Sprintf 函数。以下是修正后的代码示例:

package main

import "fmt"

func main() {
    anotherValue := "aValue"
    Banana := map[string]map[string]interface{}{
        "amap": map[string]interface{}{
            "aKey":       "aValue",
            "anotherKey": fmt.Sprintf("another Value %s", anotherValue),
        },
    }
    
    fmt.Printf("%#v\n", Banana)
}

输出结果:

map[string]map[string]interface {}{"amap":map[string]interface {}{"aKey":"aValue", "anotherKey":"another Value aValue"}}

如果你需要在映射初始化后进行动态的字符串插值,可以使用以下方法:

package main

import "fmt"

func main() {
    Banana := make(map[string]map[string]interface{})
    Banana["amap"] = make(map[string]interface{})
    
    anotherValue := "aValue"
    Banana["amap"]["aKey"] = "aValue"
    Banana["amap"]["anotherKey"] = fmt.Sprintf("another Value %s", anotherValue)
    
    fmt.Printf("%#v\n", Banana)
}

对于更复杂的格式化需求,fmt.Sprintf 支持多种格式化动词:

package main

import "fmt"

func main() {
    Banana := map[string]map[string]interface{}{
        "amap": map[string]interface{}{
            "intValue":    fmt.Sprintf("Value: %d", 42),
            "floatValue":  fmt.Sprintf("Value: %.2f", 3.14159),
            "boolValue":   fmt.Sprintf("Value: %t", true),
            "multiValue":  fmt.Sprintf("Values: %s %d %.2f", "test", 100, 2.718),
        },
    }
    
    fmt.Printf("%#v\n", Banana)
}

如果你的插值变量在映射初始化时不可用,可以先创建映射结构,然后单独设置格式化后的值:

package main

import "fmt"

func main() {
    Banana := map[string]map[string]interface{}{
        "amap": map[string]interface{}{
            "aKey": "aValue",
        },
    }
    
    // 稍后进行字符串插值
    dynamicValue := "dynamic"
    Banana["amap"]["anotherKey"] = fmt.Sprintf("Formatted: %s", dynamicValue)
    
    fmt.Printf("%#v\n", Banana)
}
回到顶部