这是我参与「第五届青训营 」伴学笔记创作活动的第 3 天
字符串
字符串是一个常见的一个数据类型。
| 方法 | 返回值 | 描述 |
|---|---|---|
| Contains(s, subStr string) | bool | Contains reports whether substr is within s. |
| Count(s, subStr string) | int | Count counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s. |
| HasPrefix(s, prefix string) | bool | HasPrefix tests whether the string s begins with prefix. |
| HasSuffix(s, sfuffix string) | bool | HasSuffix tests whether the string s ends with suffix. |
| Index(s, subStr string) | int | Index returns the index of the first instance of substr in s, or -1 if substr is not present in s. |
| Join(elems []string, sep string) | string | Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string. |
| Repeat(s string, count int) | string | Repeat returns a new string consisting of count copies of the string s. It panics if count is negative or if the result of (len(s) * count) overflows. |
| Replace(s, old, new string, n int) | string | 字符串替换,原有字串,替换的新串和替换次数 |
| Split(s, sep string) | []string | 分割字符串 |
| ToUpper(s string) | string | 转换为大写 |
| ToLower(s string) | string | 转换为小写 |
字符串格式化
字符串的格式化需要使用 fmt.Printf 函数来完成。
%v:简单打印值的内容%+v:打印值的内容加上字段的名称%#v:打印值的内容加上字段的名称,以及结构体的类型
fmt.Printf("p=%v\n", p) // p={1 2}
fmt.Printf("p=%+v\n", p) // p={x:1 y:2}
fmt.Printf("p=%#v\n", p) // p=main.point{x:1, y:2}
其他的格式化输出,就和C语言类似了,例如,%.2f, %d, %p 等等
字符串和 JSON
字符串可以通过 encoding/json 来进行结构体和字符串的序列化和反序列化。
type userInfo struct {
Name string
Age int `json:"age"`
Hobby []string
}
// 序列化
a := userInfo{
Name: "wang",
Age: 18,
Hobby: []string{"Golang", "TypeScript"}
}
buf, err := json.Marshal(a)
// 反序列化
var b userInfo
err = json.Unmarshal(buf, &b)
| 方法 | 描述 |
|---|---|
| Marshal(a any) ([]byte, error) | 将任何类型序列化为字符串字节序列 |
| Unmarshal(data []byte, v any) error | 将字符串字节序列反序列化为结构体实例 |
函数
函数在上面 HelloWorld中的 func main() { /* */} 就已经是一个函数了,不管任何语言,函数都是一个重要的执行单元。Go语言的函数主要有下面几个部分:
func关键字- 函数名称:函数的名称
- 参数列表:可以是空参也可以是多个参数
- 返回值列表:这里注意一下,go语言的返回值支持多个
// 多个参数一个返回值
func add(a, b int) int {
return a + b
}
// 多个参数多个返回值
func contains(m map[string]int, k string) (string v, ok bool) {
v, ok := m[k]
return v, ok
}
结构体方法
结构体是一个数据类型,结构体也可以对其附加函数,也就是结构体方法。这很类似于面向对象语言里面的成员方法。
func (u user) checkPassword(paswd string) bool {}
func (u *user) resetPassword(paswd string) bool {}
函数和结构体方法调用上的一个区别:
u := user{ name: "Alice", password: "1234" }
// 普通函数
checkPassword(u, "12345")
// 结构体方法
u.checkPassword("2345")
指针
Go语言有类似于 C/C++ 的指针,可以进行一些简单的指针操作:
- 取地址:
& - 解引用:
*
// 定义一个函数操作引用
func increment(n *int) {
*n = *n + 1
}
// 使用这个函数
n := 1
increment(&n) // n 变量完成自增
就如同上面这个例子所示,可以通过指针完成对变量的一个操作。
常用库
时间工具库
字符串转换工具库
strconv 提供了大量字符串转换的函数,便于字符串和各种数据类型之间的转换。
| 方法 | 返回值 | 描述 |
|---|---|---|
| ParseFloat(s string, bitSize int) | float64 | 将字符串转换为64位或者32位的浮点数 |
| ParseInt(s string, base int, bitSize int) | int64, error | 将整数字符串转换为指定进制的整数。base:进制,2,8,10,16,如果是 0 代表字符串的前缀决定数字的进制 |
| Atoi(s string) | int | Atoi is equivalent to ParseInt(s, 10, 0), converted to type int. |
import (
"fmt"
"strconv"
)
func main() {
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f) // 1.234
n, _ := strconv.ParseInt("111", 10, 64)
fmt.Println(n) // 111
n, _ = strconv.ParseInt("0x1000", 0, 64)
fmt.Println(n) // 4096
n2, _ := strconv.Atoi("123")
fmt.Println(n2) // 123
n2, err := strconv.Atoi("AAA")
fmt.Println(n2, err) // 0 strconv.Atoi: parsing "AAA": invalid syntax
}
系统工具库
系统库主要有两部分:os 和 os/exec 。常用的主要有以下几个:
os.Args: 获取执行参数os.Getenv(key string): 获取环境变量os.Setenv(key, value string): 获取环境变量exec.Command(name string, args ...string): 执行
import (
"fmt"
"os"
"os/exec"
)
func main() {
// go run example/20-env/main.go a b c d
fmt.Println(os.Args)
fmt.Println(os.Getenv("PATH"))
fmt.Println(os.Setenv("AA", "BB"))
buf, err := exec.Command(
"grep",
"127.0.0.1",
"/etc/hosts").CombinedOutput()
if err != nil {
panic(err)
}
fmt.Println(string(buf))
// 127.0.0.1 localhost
}