试图了解Golang多元化

时间:2018-07-18 06:57:08

标签: go pluralize cldr

我试图理解Go中的多元性。文档https://godoc.org/golang.org/x/text/message/catalog#hdr-String_interpolation中的示例不起作用。方法plural.Select不存在。它应该是plural.Selectf。请注意最后的f

message.Set(language.English, "You are %d minute(s) late.",
catalog.Var("minutes", plural.Selectf(1, "one", "minute")),
catalog.String("You are %d ${minutes} late."))
p := message.NewPrinter(language.English)
p.Printf("You are %d minute(s) late.", 5)

我在https://phraseapp.com/blog/posts/internationalization-i18n-go/处找到了另一个教程。这段代码可以正常工作

message.Set(language.English, "You have %d problem",
    catalog.Var("minutes", plural.Selectf(1, "%d", "one", "minute", "other", "minutes")),
    catalog.String("You are %d ${minutes} late."))
printer := message.NewPrinter(language.English)
printer.Printf("You have %d problem", 1)
printer.Println()
printer.Printf("You have %d problem", 3)
printer.Println()

// result
// You are 1 minute late.
// You are 3 minutes late.

两个示例都使用高级字符串插值。现在,我试图了解plural.Selectf。第一个参数1在做什么?为什么需要第二个参数%d?我想我理解其余的

"one"  : "minute"
"other": "minutes"

我还在%[1]d中看到了catalog.String。这是做什么的?

非常感谢!我现在很困惑。

1 个答案:

答案 0 :(得分:2)

您在这里!

plural.Selectf的第一个参数是int。因此它可以是任何有效的整数。 第二个参数是string。它应该是格式动词,即%d%s%f 第三个参数是一个空接口,可以接收任何类型,即字符串,struct,catalog.Message,..

让我们举个例子,

func main() {

    var (
            msg = plural.Selectf(2, "%d",
                "=10", "%[1]d task and %[2]d processes remaining!", // interface 1
                "=1", "%[1]d task and %[2]d processes", // interface 2
                "other", "%d tasks and %d processes!" // interface 3
            )
            key = "%d task - %d process"
            tag = "en"
        )

        lTag := language.MustParse(tag)
        message.Set(lTag, key, msg)

        p := message.NewPrinter(language.English)
        p.Printf("%d task - %d process", 1, 10)

}

在这里,我们用英语创建了NewPrinter,并为标签%d task(s) remaining!(英语的短代码)设置了带有键en的翻译消息。

执行p.Printf("%d task - %d process", 1, 3)行时,转换机制将采用第一个参数(格式说明符),即%d task - %d process,并与我们在en标记中设置的键进行比较来检查消息。如果找到了密钥,则它将处理消息,即msg

这里Selectf的第一个参数说是从nth中获取Printf(在我们的情况下为第二个)格式动词的值(即%d的第二个值为10)并进行比较带有案例选择器,即案例1(界面1)中的=10。如果比较成功,则返回处理后的值,即案例1中的1 task and 10 processes

如果Printf收到的第二个%d的值不是1和10,则它将返回情况3(接口3)的值

然后

%[n]d的使用方式可以

fmt.Printf("%[2]d %[1]d\n", 11, 22)并显示22 11

希望,这对您有帮助。