1

我试图理解 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这是做什么的?

非常感谢!我现在超级迷茫。

4

1 回答 1

4

干得好!

的第一个参数plural.Selectf是一个int。所以它可以是任何有效的整数。第二个参数是一个string。它应该是一个格式动词 ie %dor %sor%f 第三个参数是一个空接口,可以接收任何类型 ie string, 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)line 执行时,翻译机制接受第一个参数(格式说明符) ie并通过与我们在标签%d task - %d process中设置的键进行比较来检查消息。en如果找到密钥,则处理消息,即msg.

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

如果Printf接收到的第二个 %d 的值不是 1 和 10,那么它将从案例 3(接口 3)返回值

和,

%[n]d可以像这样使用,

fmt.Printf("%[2]d %[1]d\n", 11, 22)它打印出来22 11

希望,这对你有帮助。

于 2018-07-18T11:29:10.667 回答