方括号在表示复制目标数组时有什么意义?

huangapple go评论88阅读模式
英文:

What is the significance of square brackets in denoting the copy destination array?

问题

我一直在熟悉如何在Go语言中切片和切割数组/切片(实际任务是检查字节切片中的前N个字节是否是一组特定的字节)。

所以我学会了如何将切片中的字节复制到数组中:

var dstArray [1]byte
srcSlice := []byte{0x00}
copy(dstArray[:], srcSlice)

然而,让我困惑的是在copy调用中为什么需要在dstArray的末尾写上[:]。如果我省略它,就会出现以下错误:

copy的第一个参数应该是切片;现在是[1]byte

首先,为什么它说"应该是切片"?我提供的是一个数组,而且它完全正常工作(带有[:]部分)。

而且,主要问题是:为什么它需要[:]这部分?在这个上下文中它的意义是什么?如果我们省略它,指令会被误解吗?为什么要复杂化语法?

英文:

I have been getting familiar with how to slice and dice arrays/slices in Go (the actual task is to check if the first N bytes in a byte slice is a set of particular bytes).

So I have learnt how to copy bytes from a slice into an array:

var dstArray [1]byte
srcSlice := []byte{0x00}
copy(dstArray[:], srcSlice)

What puzzles my though is the necessity to write [:] at the end of dstArray in the copy call. If I omit that I get this error:

first argument to copy should be slice; have [1]byte

First of all, why does it say "should be slice"? I provide an array instead and it works just fine (with the [:] bit).

And, the main question is: why does it require the [:] bit? What is the significance of it in this context? Could the instruction be somehow misinterpreted if we omit it? Why complicate the syntax?

答案1

得分: 3

[:]是切片表达式的简写形式。

根据规范:

> 为了方便起见,任何索引都可以省略。缺少的低索引默认为零;缺少的高索引默认为切片操作数的长度:
>
>
> a[2:] // 等同于 a[2 : len(a)]
> a[:3] // 等同于 a[0 : 3]
> a[:] // 等同于 a[0 : len(a)]

参考链接:https://golang.org/ref/spec#Slice_expressions

英文:

[:] is the shorthand of slice expression.

According to the spec:

> For convenience, any of the indices may be omitted. A missing low
> index defaults to zero; a missing high index defaults to the length of
> the sliced operand:
>
>
> a[2:] // same as a[2 : len(a)]
> a[:3] // same as a[0 : 3]
> a[:] // same as a[0 : len(a)]

See also: https://golang.org/ref/spec#Slice_expressions

答案2

得分: 2

首先,为什么会说“应该是切片”?

因为这是函数的 API 定义方式,Go 是一种强类型语言,所以你应该提供所需类型的值。

我提供了一个数组,而不是切片,并且它可以正常工作(使用了 [:] 部分)。

你并没有提供一个数组,而是通过使用 [:] 将其转换为切片。这是一个示例:https://play.golang.org/p/TEih17eVWml

为什么需要 [:] 部分?

这是将数组转换为切片以符合 Copy API 的方法。

英文:

> First of all, why does it say "should be slice"?

Because this is how the API of the function is defined, go is strongly typed language, so you should provide a value of the required type.

> I provide an array instead and it works just fine (with the [:] bit).

You don't provide an array, you take an array and convert it to slice by using [:] https://play.golang.org/p/TEih17eVWml

> why does it require the [:] bit?

This is how you get a slice from Array to conform with the Copy API

huangapple
  • 本文由 发表于 2021年6月20日 18:10:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/68054750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定