Go实战--go中一些有用的代码片段(The way to go)
来源:互联网 发布:单片机最小系统的组成 编辑:程序博客网 时间:2024/04/27 06:40
生命不止,继续 go go go !!!
今天跟大家分享一些有用的,简单的golang代码片段。
改变string的值
首先我们要知道,在golang中,string是不可变的:
str := "hello" str[0] = 'c'
编译错误:cannot assign to str[0]
正确的做法:
package mainimport ( "fmt")func main() { str := "hello" c := []byte(str) c[0] = 'f' str2 := string(c) fmt.Println(str2)}
输出: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)}
输出:dog
遍历string输出
从其他语言转到golang的人来说,可能不太习惯for range,我们看看使用for range输出字符串中的每个字符:
package mainimport "fmt"func main() { value := "cat;dog" for ch := range value { fmt.Println(ch) }}
输出:
1
2
3
4
5
6
你可能发现了,把索引输出的,而不是每个字符。
package mainimport "fmt"func main() { value := "cat;dog" for _, ch := range value { fmt.Println(ch) }}
输出:
99
97
116
59
100
111
103
但是,这还不是你想要的,所以:
package mainimport "fmt"func main() { value := "cat;dog" for _, ch := range value { fmt.Println(string(ch)) }}
字符串中bytes和characters
package mainimport ( "fmt" "unicode/utf8")func main() { value := "爱情" i := utf8.RuneCountInString(value) fmt.Println(i) j := len(value) fmt.Println(j)}
输出:
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)}
输出: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)}
输出:
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)}
打开并读取文件
使用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) } }}
使用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) }}
检测某个channel是否被关闭
if input, open := <-ch; !open { break}
阅读全文
1 0
- Go实战--go中一些有用的代码片段(The way to go)
- Go实战--go中编码转换(The way to go)
- Go实战--go中使用libphonenumber(The way to go)
- Go实战--go中使用cookie(The way to go)
- Go实战--go中使用rpc(The way to go)
- Go实战--go中函数(function)和方法(method)的使用(The way to go)
- Go实战--go中函数递归(recursion)的使用(The way to go)
- Go实战--net/http中JSON的使用(The way to go)
- Go实战--go语言中执行shell脚本(The way to go)
- Go实战--go中使用google/protobuf(The way to go)
- Go实战--go中使用base64加密(The way to go)
- Go实战--go中使用hmac sha256(The way to go)
- The way to go !
- Go实战--golang新手入门常见错误(The way to go)
- Go实战--golang生成uuid(The way to go)
- Go实战--实现一个自己的网络请求日志httplogger(The way to go)
- Go实战--实现一个简单的tcp服务端和客户端(The way to go)
- Go实战--实现简单的restful api(The way to go)
- php-1
- gtilab 仓库操作
- final 关键字的相关问题
- Eclipse lombok安装过程,出现code=1错误
- pip出现Fatal error in launcher: Unable to create process using '"'
- Go实战--go中一些有用的代码片段(The way to go)
- mysql获取一个表中的下一个自增(id)值的方法
- 转发一份GoldenGate 配置文档
- Qt QVector清空的方法对比
- 进程间通信——消息队列
- Ubuntu中安装pycharm
- oracle job
- GIEC 2017全球互联网经济大会-北京早鸟票
- tomcat启动报错