在Golang中动态构建格式化字符串

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

Dynamically built formatting strings in Golang

问题

我正在尝试在Go语言中动态创建格式化字符串。思路是创建一个包含格式化类型的映射,然后通过循环输出不同类型的结果。

最终目标是查看格式化对输出的影响。

(我知道这个示例会产生相同的输出,但我会随着时间的推移将f更改为其他类型)

以下是一个示例:

import (
	"fmt"
	"strings"
)

var formats = []string{"%f", "%v"}
var f float32 = 1 << 24

func main() {
    for _, format := range formats {
        // 在这里生成格式化字符串
        parts := "%q => " + format + "\n"
        fmt.Printf(parts, format, f)
    }
}

编译器在parts行报错了一个int()转换:

在第11行,文件ch3/floating_point.go无法将"%q => "转换为int类型

在第11行,文件ch3/floating_point.go无效操作:"%q => " + format(类型不匹配,string和int)

我尝试过拼接字符串,但没有成功:

parts := strings.Join([]string{"%q =>", format, "\n"}, " ")
fmt.Printf(parts, format, f)

另外,fmt.Fprintf也没有帮助:

for _, format := range formats {
    // 在这里生成格式化字符串
    parts := fmt.Sprintf("%q => %s", format, format)
    fmt.Println(parts)
}
英文:

I am attempting to create a formatting string dynamically in Go. The idea is that a map is created with the formatting types. Then a loop goes through them to output the various types.

The end result is to see how the formatting affects the output.

(I appreciate the example will produce the same output, but I would change f over time to other types)

Below is an example of this:

import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

var formats = []string{&quot;%f&quot;, &quot;%v&quot;}
var f float32 = 1 &lt;&lt; 24

func main() {
    for format := range formats {
        // Generate formatting string here
        parts := &quot;%q =&gt; &quot; + format + &quot;\n&quot;
		fmt.Printf(parts, format, f)
    }
}

The compiler is complaining about a int() conversion at the parts: line:

>> at line 11, file ch3/floating_point.go cannot convert "%q => " to type int

>> at line 11, file ch3/floating_point.go invalid operation: "%q => " + format` (mismatched types string and int)

I have attempted joining strings, but no luck:

parts:= strings.Join([]string{&quot;%q =&gt;&quot;,format,&quot;\n&quot;), &quot; &quot;)
fmt.Printf(parts,format,f)

Also fmt.Fprintf isn't helping either:

for format := range formats {
      // Generate formatting string here
      parts := fmt.Fprintf(&quot;%q =&gt; &quot; + format, format, f)
      fmt.Println(parts)
    }

答案1

得分: 5

问题出在你的 for format := range formats 结构中。请记住,range formats 会返回两个值:切片中的实际值和其索引(索引是第一个值)。所以 &quot;%q =&gt; &quot; + format + &quot;\n&quot; 实际上会尝试将 &quot;%s =&gt; &quot; 与数值迭代索引连接起来。

如果你想遍历切片中包含的值,请使用以下循环:

for _, format := range formats {
    // ...
}
英文:

The issue is in your for format := range formats construct. Keep in mind that range formats will return two values: the actual value from the slice *and its index (which is the first value). So &quot;%q =&gt; &quot; + format + &quot;\n&quot; will actually try to concatenate &quot;%s =&gt; &quot; with the numeric iteration index.

If you want to iterate over the values contained in the slice, use the following loop for that:

for _, format := range formats {
    // ...
}

答案2

得分: 1

参见golang For空白标识符

> 如果你要遍历数组、切片、字符串或映射,或者从通道中读取数据,可以使用range子句来管理循环。
>
> for key, value := range oldMap {
> newMap[key] = value
> }

遍历数组的正确方式

for index, value := range formats {

如果你想跳过索引,可以这样做

for _, value := range formats {
英文:

See golang For and blank identifier

> If you're looping over an array, slice, string, or map, or reading
> from a channel, a range clause can manage the loop.
>
> for key, value := range oldMap {
> newMap[key] = value
> }

Right way to range with array

for index, value := range formats {

if you want to skip index do

for _, value := range formats {

huangapple
  • 本文由 发表于 2016年1月3日 23:55:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/34578466.html
匿名

发表评论

匿名网友

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

确定