sách gpt4 ăn đã đi

go - Không thể sử dụng type[]rune làm loại rune trong phần bổ sung

In lại 作者:IT王子 更新时间:2023-10-29 01:17:38 26 4
mua khóa gpt4 giày nike

gói chính

var lettersLower = []rune("abcdefghijklmnopqrstuvwxyz")
var lettersUpper = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

hàm main() {
x := append(lettersLower, lettersUpper)
}

为什么这不起作用?如何 append lettersLowerlettersUpper?

prog.go:7: cannot use lettersUpper (type []rune) as type rune in append

https://play.golang.org/p/ovx_o2rKPC

câu trả lời hay nhất

是因为thêm vào doesn't take a list to append, but rather one or more mặt hàng to append .您可以在 thêm vào 的第二个参数上使用 ... 来适应这一点:

gói chính

nhập khẩu "fmt"

var lettersLower = []rune("abcdefghijklmnopqrstuvwxyz")
var lettersUpper = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

hàm main() {
x := append(lettersLower, lettersUpper...)
fmt.Println(len(x))
}

Try it out on the Playground .

Xin lưu ý rằngthêm vào 并不总是重新分配底层数组(这会导致性能和内存使用方面的问题)。就此示例而言,您还不错,但如果您尝试将同一内存用于多种用途,它可能会困扰您。 A(做作,可能不清楚)ví dụ :

gói chính

nhập khẩu (
"fmt"
"os"
)

hàm main() {
foo := []byte("this is a BIG OLD TEST!!\n")
tst := []byte("little test")
bar := append(foo[:10], tst...)

// now bar is right, but foo is a mix of old and new text!
fmt.Print("without copy, foo after: ")
os.Stdout.Write(foo)

// ok, now the same exercise but with an explicit copy of foo
foo = []byte("this is a BIG OLD TEST!!\n")
bar = append([]byte(nil), foo[:10]...) // copies foo[:10]
bar = append(bar, tst...)

// this time we modified a copy, and foo is its original self
fmt.Print("with a copy, foo after: ")
os.Stdout.Write(foo)
}

当您尝试在 append 到 đồ ăn 的子 slice 后打印它时,您会得到新旧内容的奇怪混合。

在共享底层数组有问题的地方,您可以使用字符串(字符串字节是不可变的,可以非常有效地防止意外覆盖)或者像我对 append([]byte(nil) , foo[:10]...) 以上。

关于go - 不能在追加中使用类型 []rune 作为类型 rune,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28640097/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress