golang 数组面试题

第一题 array append扩容问题

实例代码array_append.go

\/**
  * Author: JeffreyBool
  * Date: 2019\/4\/17
  * Time: 16:16
  * Software: GoLand
*\/

package array

\/**
 * arr 底层扩容知识点
 *\/
func ArrayAppend() []int {
    arr := make([]int,5)
    arr = append(arr,10)
    \/\/问现在 arr 结果是什么
    return arr
}

测试代码array_append_test.go

\/**
  * Author: JeffreyBool
  * Date: 2019\/4\/17
  * Time: 16:18
  * Software: GoLand
*\/

package array

import (
    "testing"
)

func TestArray_append(t *testing.T) {
    arr := ArrayAppend()
    t.Log(arr)
}

本题讲解

make 函数

make 也是内建函数,你可以从 http:\/\/golang.org\/pkg\/builtin\/#make 看到它, 它的函数原型 比 new 多了一个(长度)参数,返回值也不同。
函数原型是

func make(Type, size IntegerType) Type 
  • 第一个参数是一个类型,第二个参数是长度
  • 返回值是一个类型

官方描述为:

The make built-in function allocates and initializes an object(分配空间 + 初始化) of type slice, map or chan(only). Like new , the first arguement 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.
翻译为:
内建函数 make 分配并且初始化 一个 slice, 或者 map 或者 chan 对象。 并且只能是这三种对象。 和 new 一样,第一个参数是 类型,不是一个值。 但是make 的返回值就是这个类型(即使一个引用类型),而不是指针。 具体的返回值,依赖具体传入的类型。

Slice : 第二个参数 size 指定了它的长度,此时它的容量和长度相同。
你可以传入第三个参数 来指定不同的容量值,但是必须不能比长度值小。
比如: make([]int, 0, 10)
Map: 根据size 大小来初始化分配内存,不过分配后的 map 长度为0。 如果 size 被忽略了,那么会在初始化分配内存的时候 分配一个小尺寸的内存。
Channel: 管道缓冲区依据缓冲区容量被初始化。如果容量为 0 或者被 忽略,管道是没有缓冲区的。

  • 根据上面 make 的解释我们可以得知Slice可以设定三个参数, 第一个是类型,第二个是长度,第三个是大小, 当Slice 大小不够了会自动扩容.
arr := make([]int,5) 
\/\/实际译为
arr := make([]int,5,5)

arr 的大小,长度都为5.

我们将代码稍微改良下:

\/**
  * Author: JeffreyBool
  * Date: 2019\/4\/17
  * Time: 16:16
  * Software: GoLand
*\/

package array

import (
    "fmt"
)

\/**
 * arr 底层扩容知识点
 *\/
func ArrayAppend() []int {
    arr := make([]int,5)
    fmt.Printf("arr.len: %d; arr.cap: %d \n

猜你喜欢

转载自blog.csdn.net/cpongo7/article/details/89463893