在Go 1.18中,strings.Title()已被弃用。现在应该使用什么?以及如何使用?

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

In Go 1.18 strings.Title() is deprecated. What to use now? And how?

问题

根据这里的建议,人名应该像John William Smith一样首字母大写。

我正在使用Golang编写一个小型软件,从用户的表单输入中获取姓和名。

在Go 1.18之前,我使用的是:

lastname = strings.Title(strings.ToLower(strings.TrimSpace(lastname)))
firstname = strings.Title(strings.ToLower(strings.TrimSpace(firstname)))

这个方法是有效的,但是现在Go 1.18已经弃用了strings.Title()

他们建议使用golang.org/x/text/cases代替。

所以我认为我应该将我的代码改成这样:

caser := cases.Title(language.Und)

lastname = caser.Title(strings.ToLower(strings.TrimSpace(lastname)))
firstname = caser.Title(strings.ToLower(strings.TrimSpace(firstname)))

这个方法和之前的方法效果是一样的。

不同之处在于荷兰语单词ijsland应该被转换为IJsland而不是Ijsland

问题

在这一行中caser := cases.Title(language.Und),我使用了Und,因为我不知道应该使用什么语言标签

我应该使用language.English还是language.AmericanEnglish或其他标签?

到目前为止,好像strings.Title()是使用Und还是English

英文:

As suggested here names of people should be capitalized like John William Smith.

I'm writing a small software in Golang which gets last and first name from user's form inputs.

Until Go 1.18 I was using:

lastname = strings.Title(strings.ToLower(strings.TrimSpace(lastname)))
firstname = strings.Title(strings.ToLower(strings.TrimSpace(firstname)))

It works but now Go 1.18 has deprecated strings.Title().

They suggest to use golang.org/x/text/cases instead.

So I think I should change my code in something like this:

caser := cases.Title(language.Und)

lastname = caser.Title(strings.ToLower(strings.TrimSpace(lastname)))
firstname = caser.Title(strings.ToLower(strings.TrimSpace(firstname)))

It works the same as before.

The difference is for Dutch word like ijsland that should be titled as IJsland and not Ijsland.

The question

In the line caser := cases.Title(language.Und) I'm using Und because I don't know what language Tag to use.

Should I use language.English or language.AmericanEnglish or other?

So far it was like strings.Title() was using Und or English?

答案1

得分: 17

如文档中所提到的,strings.Title已被弃用,你应该使用cases.Title代替。

> 弃用:Title规则在处理Unicode标点时不正确。请使用golang.org/x/text/cases。

以下是如何从两个角度使用它的示例代码:

// 直接的方法
caser := cases.Title(language.BrazilianPortuguese)
titleStr := caser.String(str)

// Transformer接口感知的方法
src := []byte(s)
dest := []byte(s) // dest也可以是`dest := src`
caser := cases.Title(language.BrazilianPortuguese)
_, _, err := caser.Transform(dest, src, true)

请确保查看transform.Transformer.Transformcases.Caser以了解每个参数和返回值的含义,以及工具的限制。例如:

> Caser可能具有状态,并且因此不应在goroutine之间共享。

关于要使用的language,你应该注意它们在结果上的差异,除此之外,任何选择都应该没问题。以下是煎鱼关于差异的总结的摘录,对我来说很清楚:

Go Playground: https://go.dev/play/p/xp59r1BkC9L

func main() {
    src := []string{
        "hello world!",
        "i with dot",
        "'n ijsberg",
        "here comes O'Brian",
    }
    for _, c := range []cases.Caser{
        cases.Lower(language.Und),
        cases.Upper(language.Turkish),
        cases.Title(language.Dutch),
        cases.Title(language.Und, cases.NoLower),
    } {
        fmt.Println()
        for _, s := range src {
            fmt.Println(c.String(s))
        }
    }
}

输出如下:

hello world!
i with dot
'n ijsberg
here comes o'brian

HELLO WORLD!
İ WİTH DOT
'N İJSBERG
HERE COMES O'BRİAN

Hello World!
I With Dot
'n IJsberg
Here Comes O'brian

Hello World!
I With Dot
'N Ijsberg
Here Comes O'Brian
英文:

As mentioned in documentation strings.Title is deprecated and you should use cases.Title instead.

> Deprecated: The rule Title uses for word boundaries does not handle
> Unicode punctuation properly. Use golang.org/x/text/cases instead.

Here is an example code of how to use it as from two perspectives:

// Straightforward approach
caser := cases.Title(language.BrazilianPortuguese)
titleStr := caser.String(str)

// Transformer interface aware approach
src := []byte(s)
dest := []byte(s) // dest can also be `dest := src`
caser := cases.Title(language.BrazilianPortuguese)
_, _, err := caser.Transform(dest, src, true)

Make sure to take a look on the transform.Transformer.Transform and cases.Caser in order to understand what each parameter and return values mean, as well as the tool's limitations. For example:

> A Caser may be stateful and should therefore not be shared between
> goroutines.

Regarding what language to use, you should be aware of their difference in the results, besides that, you should be fine with any choice. Here is a copy from 煎鱼's summary on the differences that cleared it for me:

Go Playground: https://go.dev/play/p/xp59r1BkC9L

func main() {
    src := []string{
        "hello world!",
        "i with dot",
        "'n ijsberg",
        "here comes O'Brian",
    }
    for _, c := range []cases.Caser{
        cases.Lower(language.Und),
        cases.Upper(language.Turkish),
        cases.Title(language.Dutch),
        cases.Title(language.Und, cases.NoLower),
    } {
        fmt.Println()
        for _, s := range src {
            fmt.Println(c.String(s))
        }
    }
}

With the following output

hello world!
i with dot
'n ijsberg
here comes o'brian

HELLO WORLD!
İ WİTH DOT
'N İJSBERG
HERE COMES O'BRİAN

Hello World!
I With Dot
'n IJsberg
Here Comes O'brian

Hello World!
I With Dot
'N Ijsberg
Here Comes O'Brian

答案2

得分: 6

到目前为止,strings.Title()函数使用的是UndEnglish吗?

strings.Title()函数基于ASCII字符工作,而cases.Title()函数基于Unicode字符工作,无法获得完全相同的行为。

我应该使用language.Englishlanguage.AmericanEnglish还是其他的?

language.Englishlanguage.AmericanEnglishlanguage.Und似乎都遵循相同的标题规则。使用其中任何一个应该能够最接近原始的strings.Title()行为。

使用支持Unicode的这个包的整个目的是更加准确。因此,请选择适合您用户的标签。

英文:

> So far it was like strings.Title() was using Und or English?

strings.Title() works based on ASCII, where cases.Title() works based on Unicode, there is no way to get the exact same behavior.

> Should I use language.English or language.AmericanEnglish or other?

language.English, language.AmericanEnglish and language.Und all seem to have the same Title rules. Using any of them should get you the closest to the original strings.Title() behavior as you are going to get.

The whole point of using this package with Unicode support is that it is objectively more correct. So pick a tag appropriate for your users.

答案3

得分: 3

strings.Title(str)已被弃用,应更改为cases.Title(language.Und, cases.NoLower).String(str)

package main
import (
	"fmt"
	"strings"
	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)
func main() {
	fmt.Println(strings.Title("abcABC"))                                   // AbcABC
	fmt.Println(cases.Title(language.Und, cases.NoLower).String("abcABC")) // AbcABC
}

Playground: https://go.dev/play/p/i0Eqh3QfxTx

英文:

strings.Title(str) was deprecated, should change to cases.Title(language.Und, cases.NoLower).String(str)

package main
import (
	"fmt"
	"strings"
	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)
func main() {
	fmt.Println(strings.Title("abcABC"))                                   // AbcABC
	fmt.Println(cases.Title(language.Und, cases.NoLower).String("abcABC")) // AbcABC
}

Playground : https://go.dev/play/p/i0Eqh3QfxTx

答案4

得分: 1

这是一个简单的示例,演示如何使用golang.org/x/text包将变量中每个字符串值的首字母大写。

package main

import (
	"fmt"

	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)

func main() {
	sampleStr := "with value lower,  all the letters are lowercase. this is good for poetry perhaps"
	caser := cases.Title(language.English)
	fmt.Println(caser.String(sampleStr))
}

输出:With Value Lower, All The Letters Are Lowercase. This Is Good For Poetry Perhaps

Playground示例:https://go.dev/play/p/_J8nGVuhYC9

英文:

Here is a straightforward example of how to capitalize the initial letter of each string value in the variable using the golang.org/x/text package.

package main

import (
	"fmt"

	"golang.org/x/text/cases"
	"golang.org/x/text/language"
)

func main() {
	sampleStr := "with value lower,  all the letters are lowercase. this is good for poetry perhaps"
	caser := cases.Title(language.English)
	fmt.Println(caser.String(sampleStr))
}

Output : With Value Lower, All The Letters Are Lowercase. This Is Good For Poetry Perhaps

Playground Example: https://go.dev/play/p/_J8nGVuhYC9

huangapple
  • 本文由 发表于 2022年3月26日 01:09:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/71620717.html
匿名

发表评论

匿名网友

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

确定