生命不止,继续 go go go !!!
今天跟大家分享一些有用的,简单的golang代码片段。
改变string的值
首先我们要知道,在golang中,string是不可变的:
str := "hello" str[0] = 'c'12
编译错误:cannot assign to str[0]
正确的做法:
package mainimport ( "fmt")func main() { str := "hello" c := []byte(str) c[0] = 'f' str2 := string(c) fmt.Println(str2)}123456789101112131415
输出:fello
获得子字符串
在golang中,没有substring类似的函数,但是我们如何获得子字符串呢?
答案是使用slice,切片:
package mainimport "fmt"func main() { value := "cat;dog" // Take substring from index 4 to length of string. substring := value[4:len(value)] fmt.Println(substring)}123456789101112
输出:dog
遍历string输出
从其他语言转到golang的人来说,可能不太习惯for range,我们看看使用for range输出字符串中的每个字符:
package mainimport "fmt"func main() { value := "cat;dog" for ch := range value { fmt.Println(ch) }}12345678910111213
输出:
1
2
3
4
5
6
你可能发现了,把索引输出的,而不是每个字符。
package mainimport "fmt"func main() { value := "cat;dog" for _, ch := range value { fmt.Println(ch) }}12345678910111213
输出:
99
97
116
59
100
111
103
但是,这还不是你想要的,所以:
package mainimport "fmt"func main() { value := "cat;dog" for _, ch := range value { fmt.Println(string(ch)) }}12345678910111213
字符串中bytes和characters
package mainimport ( "fmt" "unicode/utf8")func main() { value := "爱情" i := utf8.RuneCountInString(value) fmt.Println(i) j := len(value) fmt.Println(j)}123456789101112131415161718
输出:
2
6
在二维数组或切片中查询某个值
package mainimport ( "fmt")func main() { v := 11 arr2Dim := [2][2]int{} arr2Dim[0][0] = 1 arr2Dim[0][1] = 11 arr2Dim[1][0] = 111 arr2Dim[1][1] = 1111 found := falseFound: for row := range arr2Dim { for column := range arr2Dim[row] { if arr2Dim[row][column] == v { found = true break Found } } } fmt.Println(found)}12345678910111213141516171819202122232425262728293031
输出:true
检查map中是否存在某个key
package mainimport ( "fmt")func main() { map1 := map[string]int{"one": 1, "two": 2} val1, isPresent := map1["one"] fmt.Println(val1) fmt.Println(isPresent) val2, isPresent2 := map1["three"] fmt.Println(val2) fmt.Println(isPresent2)}1234567891011121314151617
输出:
1
true
0
false
检测某个值是否实现了某一接口
package mainimport ( . "launchpad.net/gocheck" "testing")func Test(t *testing.T) { TestingT(t)}type MySuite struct{}var _ = Suite(&MySuite{})type IFoobar interface { foobar()}type Foobar struct {}func (f *Foobar) foobar() {}func (s *MySuite) TestFoobar(c *C) { v := Foobar{} var i interface{} = v _, ok := i.(IFoobar) c.Assert(ok, Equals, false) var p interface{} = &v _, ok = p.(IFoobar) c.Assert(ok, Equals, true)}1234567891011121314151617181920212223242526272829303132333435
打开并读取文件
使用os.Open
package mainimport ( "io" "os")func main() { // open input file fi, err := os.Open("input.txt") if err != nil { panic(err) } // close fi on exit and check for its returned error defer func() { if err := fi.Close(); err != nil { panic(err) } }() // open output file fo, err := os.Create("output.txt") if err != nil { panic(err) } // close fo on exit and check for its returned error defer func() { if err := fo.Close(); err != nil { panic(err) } }() // make a buffer to keep chunks that are read buf := make([]byte, 1024) for { // read a chunk n, err := fi.Read(buf) if err != nil && err != io.EOF { panic(err) } if n == 0 { break } // write a chunk if _, err := fo.Write(buf[:n]); err != nil { panic(err) } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
使用outil.ReadFile
package mainimport ( "io/ioutil")func main() { // read the whole file at once b, err := ioutil.ReadFile("input.txt") if err != nil { panic(err) } // write the whole body at once err = ioutil.WriteFile("output.txt", b, 0644) if err != nil { panic(err) }}12345678910111213141516171819
检测某个channel是否被关闭
if input, open :=