修复数组替换中引用错误的切片

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

Fixing improperly referenced slices in an array replacement

问题

以下是代码的翻译版本:

// 以下的 Go 代码无法编译,因为(我认为)指针引用的方式存在错误。

// 特别地,错误信息如下:

// prog.go:13: cannot use append((*x)[:remove], (*x)[remove + 1:]...) (type []int) as type *[]int in assignment

// 这是一个抽象和简化版本的代码,会导致上述错误信息。

package main

import "fmt"

func main() {

	x := &[]int{11, 22, 33, 44, 55, 66, 77, 88, 99}

	for i, addr := range *x {
		if addr == 22 {
			for len(*x) > 5 {
				remove := (i + 1) % len(*x)
				x = append((*x)[:remove], (*x)[remove+1:]...)
			}
			break
		}
	}

	fmt.Println(x)
}

希望对你有帮助!

英文:

The following go code doesn't compile, because (I believe) there is a mistake around the way pointers are being referenced.

In particular, The error message is

prog.go:13: cannot use append((*x)[:remove], (*x)[remove + 1:]...) (type []int) as type *[]int in assignment

Here is an abstracted and simplified version of the code which results in this error message.

package main

import "fmt"

func main() {

	x := &[]int{11, 22, 33, 44, 55, 66, 77, 88, 99}

	for i, addr := range *x {
		if addr == 22 {
			for len(*x) > 5 {
				remove := (i + 1) % len(*x)
				x = append((*x)[:remove], (*x)[remove+1:]...)
			}
			break
		}
	}

	fmt.Println(x)
}

答案1

得分: 2

你在这里并没有使用数组,而是使用了切片。通常情况下,你不希望处理指向切片的指针,因为这可能会变得很麻烦,并且只有在非常少的情况下才需要使用指针。

要修复你的错误,请对 x 进行解引用:

*x = append((*x)[:remove], (*x)[remove+1:]...)

但是你可能应该直接使用切片值,这样就不需要解引用:

x := []int{11, 22, 33, 44, 55, 66, 77, 88, 99}
英文:

You're not using an array here, you're using a slice. Generally, you don't want to handle a pointer to a slice since it can get awkward, and the pointer is needed in very few cases.

To fix your error, dereference x:

*x = append((*x)[:remove], (*x)[remove+1:]...)

But you should probably be using the slice value directly, so that no dereferences are required:

x := []int{11, 22, 33, 44, 55, 66, 77, 88, 99}

huangapple
  • 本文由 发表于 2015年9月25日 04:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/32770650.html
匿名

发表评论

匿名网友

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

确定