`*[]int` 和 `[]*int` 的区别是什么?

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

Difference between '*[]int' vs '[]*int'

问题

*[]int[]*int 在Go语言中有什么区别?能否给我一个详细的解释?

英文:

What's the difference between *[]int and []*int in Go, can someone gives me an in-depth explanation of the same?

答案1

得分: 2

  • *[]int:指向 int 切片的指针
  • []*int:指向 int 的指针切片

示例程序:

package main

import "fmt"

func main() {
	x := []int{1, 2, 3}

	// y 是指向 int 切片的指针
	y := &x
	fmt.Printf("%T -> %v\n", y, y)

	// 切片 z 中的每个元素都是指向 int 的指针
	z := []*int{&x[0], &x[1], &x[2]}
	fmt.Printf("%T -> %v\n", z, z)
}

输出:

*[]int -> &[1 2 3]
[]*int -> [0xc0000aa000 0xc0000aa008 0xc0000aa010]
英文:
  • *[]int: Pointer to a slice of int
  • []*int: Slice of pointer to int

Sample Program:

package main

import "fmt"

func main() {
	x := []int{1, 2, 3}

	// y is a pointer to a slice of int
	y := &x
	fmt.Printf("%T -> %v\n", y, y)

	// Every element in the slice z is a pointer
	// to an int.
	z := []*int{&x[0], &x[1], &x[2]}
	fmt.Printf("%T -> %v\n", z, z)
}

Output:

*[]int -> &[1 2 3]
[]*int -> [0xc0000aa000 0xc0000aa008 0xc0000aa010]

huangapple
  • 本文由 发表于 2021年6月17日 08:56:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68011602.html
匿名

发表评论

匿名网友

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

确定