有没有办法获取切片的长度/容量地址?

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

Is there a way get slice's len/cap address?

问题

我知道有len()cap()函数可以返回切片的长度和容量,但我想要获取切片的地址,以便手动修改它。

英文:

I know there are len() and cap() functions that return len/cap of slice, but I want to get address of slice to modify it by hand.

答案1

得分: -1

package main

import (
	"fmt"
	"reflect"
	"unsafe"
)

func main() {
	// int类型的切片
	us := []int{1, 2, 3, 4}

	// 长度: 4, 容量: 4
	fmt.Printf("长度: %d, 容量: %v\n", len(us), cap(us))

	hdr := (*reflect.SliceHeader)(unsafe.Pointer(&us))
	hdr.Cap = 10
	hdr.Len = 100

	// 长度: 100, 容量: 10
	fmt.Printf("长度: %d, 容量: %v\n", len(us), cap(us))
}

输出结果:

长度: 4, 容量: 4
长度: 100, 容量: 10
英文:
package main

import (
	"fmt"
	"reflect"
	"unsafe"
)

func main() {
	// slice of int
	us := []int{1, 2, 3, 4}

	// len: 4, cap: 4
	fmt.Printf("len: %d, cap: %v\n", len(us), cap(us))

	hdr := (*reflect.SliceHeader)(unsafe.Pointer(&us))
	hdr.Cap = 10
	hdr.Len = 100

	// len: 100, cap: 10
	fmt.Printf("len: %d, cap: %v\n", len(us), cap(us))
}

Sample output:

len: 4, cap: 4
len: 100, cap: 10

huangapple
  • 本文由 发表于 2021年5月24日 17:20:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/67669551.html
匿名

发表评论

匿名网友

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

确定