如何解决需要使用“ exp / utf8string”将代码转换为更高的标准库代码
安装包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ô
解决方法
我正在尝试从 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编写此示例代码?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。