可变长参数

GO语言允许一个函数把任意数量的值作为参数,GO语言内置了**...操作符,在函数的最后一个形参才能使用...**操作符,使用它必须注意如下事项:

nil
func test(a int, b ...int){
  return
}
append
var sl []int
sl = append(sl, 1)
sl = append(sl, sl...)

append方法定义如下:

//	slice = append(slice, elem1, elem2)
//	slice = append(slice, anotherSlice...)
func append(slice []Type, elems ...Type) []Type

声明不定长数组

数组是有固定长度的,我们在声明数组时一定要声明长度,因为数组在编译时就要确认好其长度,但是有些时候对于想偷懒的我,就是不想写数组长度,有没有办法让他自己算呢?当然有,使用**...**操作符声明数组时,你只管填充元素值,其他的交给编译器自己去搞就好了;

a := [...]int{1, 3, 5} // 数组长度是3,等同于 a := [3]{1, 3, 5}
index
a := [...]int{1: 20, 999: 10} // 数组长度是100, 下标1的元素值是20,下标999的元素值是10,其他元素值都是0
init
maininitinitinitinit
initinit
initsync.Onceinitinitpprofinitinit
//go/1.15.7/libexec/src/cmd/trace/pprof.go
func init() {
 http.HandleFunc("/io", serveSVGProfile(pprofByGoroutine(computePprofIO)))
 http.HandleFunc("/block", serveSVGProfile(pprofByGoroutine(computePprofBlock)))
 http.HandleFunc("/syscall", serveSVGProfile(pprofByGoroutine(computePprofSyscall)))
 http.HandleFunc("/sched", serveSVGProfile(pprofByGoroutine(computePprofSched)))

 http.HandleFunc("/regionio", serveSVGProfile(pprofByRegion(computePprofIO)))
 http.HandleFunc("/regionblock", serveSVGProfile(pprofByRegion(computePprofBlock)))
 http.HandleFunc("/regionsyscall", serveSVGProfile(pprofByRegion(computePprofSyscall)))
 http.HandleFunc("/regionsched", serveSVGProfile(pprofByRegion(computePprofSched)))
}

忽略导包

initinit
import _ "github.com/asong"

忽略字段

在我们日常开发中,一般都是在屎上上堆屎,遇到可以用的方法就直接复用了,但是这个方法的返回值我们并不一定都使用,还要绞尽脑汁的给他想一个命名,有没有办法可以不处理不要的返回值呢?当然有,还是 _ 操作符,将不需要的值赋给空标识符:

_, ok := test(a, b int)

json序列化忽略某个字段

structjson
type Person struct{
  name string `json:"-"`
  age string `json: "age"`
}

json序列化忽略空值字段

json.Marshalstructstringnilomitempty
type User struct {
	Name  string   `json:"name"`
	Email string   `json:"email,omitempty"`
  Age int        `json: "age"`
}

func test() {
	u1 := User{
		Name: "asong",
	}
	b, err := json.Marshal(u1)
	if err != nil {
		fmt.Printf("json.Marshal failed, err:%v\n", err)
		return
	}
	fmt.Printf("str:%s\n", b)
}

运行结果:

str:{"name":"asong","Age":0}
Ageomitemptyjsonemail

短变量声明

pythonvar
var a int = 10
等用于
a := 10

使用短变量声明时有两个注释事项:

  • 短变量声明只能在函数内使用,不能用于初始化全局变量
  • 短变量声明代表引入一个新的变量,不能在同一作用域重复声明变量
  • 多变量声明中如果其中一个变量是新变量,那么可以使用短变量声明,否则不可重复声明变量;

类型断言

interfaceinterfaceinterfaceGo1.18interface{}interface{}
value, ok := x.(T)
or
value := x.(T)
interfacexx
eface_type
x
*itab*itab

切片循环

for range
// 方式一:只遍历不关心数据,适用于切片、数组、字符串、map、channel
for range T {}

// 方式二:遍历获取索引或数组,切片,数组、字符串就是索引,map就是key,channel就是数据
for key := range T{}

// 方式三:遍历获取索引和数据,适用于切片、数组、字符串,第一个参数就是索引,第二个参数就是对应的元素值,map 第一个参数就是key,第二个参数就是对应的值;
for key, value := range T{}

判断map的key是否存在

value, ok := m[key]mapkey
import "fmt"

func main() {
    dict := map[string]int{"asong": 1}
    if value, ok := dict["asong"]; ok {
        fmt.Printf(value)
    } else {
      fmt.Println("key:asong不存在")
    }
}

select控制结构

selectselectchannelGoroutinechannelchannelselectGoroutine
func fibonacci(ch chan int, done chan struct{}) {
 x, y := 0, 1
 for {
  select {
  case ch <- x:
   x, y = y, x+y
  case <-done:
   fmt.Println("over")
   return
  }
 }
}
func main() {
 ch := make(chan int)
 done := make(chan struct{})
 go func() {
  for i := 0; i < 10; i++ {
   fmt.Println(<-ch)
  }
  done <- struct{}{}
 }()
 fibonacci(ch, done)
}
selectswitchswitchselectcasechannelselectcasecasecase
selectchannelselectdefaultselect
ChannelChannelcaseChanneldefault
nil channeldefault casenil channelselect

总结

本文介绍了Go语言中的一些开发技巧,也就是Go语言的语法糖,掌握好这些可以提高我们的开发效率,你都学会了吗?

更多关于Go语言开发技巧和Go语言的语法糖请查看下面的相关链接

您可能感兴趣的文章: