关于编程语言:Go语言学习查缺补漏ing-Day2

19次阅读

共计 2258 个字符,预计需要花费 6 分钟才能阅读完成。

作者:ReganYue

起源:恒生 LIGHT 云社区

Go 语言学习查缺补漏 ing Day2

一、函数返回参数命名的一个注意事项

请大家察看上面这个函数有什么问题吗?

func fun(x, y int) (s int, error) {return x * y, nil}

尽管这个谬误,在集成开发环境 Goland 中会有提醒,然而其余的开发工具,比方 VS Code 就不晓得会不会提醒了。

咱们能够看到这个提醒:函数有命名的返回参数,也有没有命名的返回参数。

这就阐明函数有多个返回值参数时,如果你给一个参数命了名,那么其余参数也必须命名。而且如果给参数命名,那么必须给参数加上括号,无论参数个数是一个还是多个。这里给第一个参数命名为 s,而没有给第二个参数命名,所以有谬误。

二、new()和 make()有什么不同?

在 Go SDK 中,对 new 的形容是这样的:

// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type

它是一个用于分配内存的内置函数,只有一个参数。如果应用这个函数,那么就会返回一个指向一块新开拓内存的指针,这块内存是第一个参数示意的类型的零值。

咱们再来看一看 make:

// The make built-in function allocates and initializes an object of type
// slice, map, or chan (only). Like new, the first argument is a type, not a
// value. Unlike new, make's return type is the same as the type of its
// argument, not a pointer to it. The specification of the result depends on
// the type:
//  Slice: The size specifies the length. The capacity of the slice is
//  equal to its length. A second integer argument may be provided to
//  specify a different capacity; it must be no smaller than the
//  length. For example, make([]int, 0, 10) allocates an underlying array
//  of size 10 and returns a slice of length 0 and capacity 10 that is
//  backed by this underlying array.
//  Map: An empty map is allocated with enough space to hold the
//  specified number of elements. The size may be omitted, in which case
//  a small starting size is allocated.
//  Channel: The channel's buffer is initialized with the specified
//  buffer capacity. If zero, or the size is omitted, the channel is
//  unbuffered.
func make(t Type, size ...IntegerType) Type

咱们能够理解,make 也是分配内存的,然而只能给 slice, map 或者 chan 分配内存。而且这个 make 也不返回指针,而是返回你第一个参数代表的类型的值。

通过下面的介绍,咱们再来看一看这段代码是否通过编译。

import "fmt"

func main() {l := new([]int)
    l = append(l, 0)
    fmt.Println(l)
}

显然是不能的,上面是报错信息:

咱们后面讲了,new 函数 new 进去的是指针,而指针是不能进行 append 操作的。所以咱们建设 slice, map 或者 chan 最好应用 make 函数,而不要应用 new 函数。

三、切片追加切片问题

如果有两个切片,如何应用 append 把它们拼凑在一个切片外面呢?

这样行不行?

package main

import "fmt"

func main() {slice := []int{8, 8, 8}
    append_slice := []int{2, 8}
    slice = append(slice, append_slice)
    fmt.Println(slice)
}

看一看 Goland 怎么提醒的吧。

如同是不行吧。

这时咱们就要应用 ... 这种语法糖。

它有多个性能,其中的一个性能就是能够把切片打散进行传递。还有就是在定义函数时应用,能够接管任意个参数。

上面是运行后果:

四、简短模式申明变量的限度

咱们来看一看上面这一段代码,你感觉有没有什么问题?

package main

import "fmt"


var(two = 200)
one := 100

func main() {fmt.Println(one,two)
}

是有问题的。

就得来谈一谈变量的简短模式申明有哪些限度:

  1. 必须应用显示初始化,也就是手工给予初值。
  2. 不能指定数据类型,编译器会依据你指定的初值主动推理变量的类型。
  3. 只能在函数外部应用简短模式来申明变量。

咱们这里呈现谬误的起因就是触发了上述第三点限度:未在函数外部应用简短模式来申明变量。

正文完
 0