小编典典

需要使用“ exp / utf8string”将代码转换为更高的标准库代码

go

我正在尝试从 The Go Programming Language
Phrasebook


Go编程语言短语》)中获取

一个示例,该书于2012年基于Go 1.0编写。该示例使用的exp/utf8string包现已变为unicode/utf8。我目前正在使用Go
1.2.1,并且下面的代码无法按原样编译,因为该exp/utf8string软件包现已失效:

package main
import "strings"
import "unicode"
import "exp/utf8string"
import "fmt"

func main()
{
    str := "\tthe important rôles of utf8 text\n"
    str = strings.TrimFunc(str, unicode.IsSpace)

    // The wrong way
    fmt.Printf("%s\n", str[0:len(str)/2])
    // The right way
    u8 := utf8string.NewString(str)
    FirstHalf := u8.Slice(0, u8.RuneCount()/2)
    fmt.Printf("%s\n", FirstHalf)

}

我仍然是GoLang的新手,因此我不确定如何将较早的实验软件包集成到标准库中。我做了一些研究,发现utf8string.NewString(str)现在是expvar.NewString(str),所以我将进口改为

expvar
unicode

并适当地修改了代码以调用expvar.NewString(str),但是我仍然遇到两个错误:

u8.Slice undefined (type *expvar.String has no field or method Slice)
u8.RuneCount undefined (type *expvar.String has no field or method RuneCount)

我尝试了几种不同的方法,但似乎无法使其正常工作。

应该如何为GoLang 1.2.1编写此示例代码?


阅读 200

收藏
2020-07-02

共1个答案

小编典典

安装包utf8string

$ go get -v code.google.com/p/go.exp/utf8string
code.google.com/p/go.exp (download)
code.google.com/p/go.exp/utf8string
$

修复程序:

package main

import (
    "fmt"
    "strings"
    "unicode"

    "code.google.com/p/go.exp/utf8string"
)

func main() {
    str := "\tthe important rôles of utf8 text\n"
    str = strings.TrimFunc(str, unicode.IsSpace)

    // The wrong way
    fmt.Printf("%s\n", str[0:len(str)/2])
    // The right way
    u8 := utf8string.NewString(str)
    FirstHalf := u8.Slice(0, u8.RuneCount()/2)
    fmt.Printf("%s\n", FirstHalf)
}

输出:

the important r
the important rô

将程序修改为仅使用Go 1.2.1标准软件包:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "\tthe important rôles of utf8 text\n"
    str = strings.TrimSpace(str)

    // The wrong way
    fmt.Printf("%s\n", str[0:len(str)/2])
    // The right way
    r := []rune(str)
    FirstHalf := string(r[:len(r)/2])
    fmt.Printf("%s\n", FirstHalf)
}

输出:

the important r
the important rô
2020-07-02