I am trying to ran an example from The Go Programming Language Phrasebook - the book was written in 2012, based on Go 1.0 . The example uses the exp/utf8string
package, which has now become unicode/utf8
. I am currently using Go 1.2.1 and code listed below will not compile as is, since the exp/utf8string
package is now defunct:
package main
import "strings"
import "unicode"
import "exp/utf8string"
import "fmt"
func main()
{
str := "\tthe important rôles of utf8 text
"
str = strings.TrimFunc(str, unicode.IsSpace)
// The wrong way
fmt.Printf("%s
", str[0:len(str)/2])
// The right way
u8 := utf8string.NewString(str)
FirstHalf := u8.Slice(0, u8.RuneCount()/2)
fmt.Printf("%s
", FirstHalf)
}
I am a still a GoLang newbie, so I'm not sure how the older experimental packages were integrated into the standard library. I did a bit of research and found that utf8string.NewString(str)
is nowexpvar.NewString(str)
, so I changed my imports to
expvar
unicode
and modified the code appropriately to call expvar.NewString(str)
,but I'm still getting two errors:
u8.Slice undefined (type *expvar.String has no field or method Slice)
u8.RuneCount undefined (type *expvar.String has no field or method RuneCount)
I've tried a few different ways but can't seem to get it to work.
How should this example code be written for GoLang 1.2.1?
Install package 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
$
Fix the program:
package main
import (
"fmt"
"strings"
"unicode"
"code.google.com/p/go.exp/utf8string"
)
func main() {
str := "\tthe important rôles of utf8 text
"
str = strings.TrimFunc(str, unicode.IsSpace)
// The wrong way
fmt.Printf("%s
", str[0:len(str)/2])
// The right way
u8 := utf8string.NewString(str)
FirstHalf := u8.Slice(0, u8.RuneCount()/2)
fmt.Printf("%s
", FirstHalf)
}
Output:
the important r
the important rô
Revising the program to only use Go 1.2.1 standard packages:
package main
import (
"fmt"
"strings"
)
func main() {
str := "\tthe important rôles of utf8 text
"
str = strings.TrimSpace(str)
// The wrong way
fmt.Printf("%s
", str[0:len(str)/2])
// The right way
r := []rune(str)
FirstHalf := string(r[:len(r)/2])
fmt.Printf("%s
", FirstHalf)
}
Output:
the important r
the important rô
Just use the UTF8 package (http://golang.org/pkg/unicode/utf8/)
The example is extremely odd because there's no need to call "NewString" to create a UTF8 string—all strings in Go are UTF8 by default.
I'd suggest finding another resource since that Phrasebook seems so out of date as to be misleading.
Try "Go By Example" and "Way To Go".