Movatterモバイル変換


[0]ホーム

URL:


unsafe

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:0Imported by:173,618

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package unsafe contains operations that step around the type safety of Go programs.

Packages that import unsafe may be non-portable and are not protected by theGo 1 compatibility guidelines.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcAlignof

func Alignof(xArbitraryType)uintptr

Alignof takes an expression x of any type and returns the required alignmentof a hypothetical variable v as if v was declared via var v = x.It is the largest value m such that the address of v is always zero mod m.It is the same as the value returned byreflect.TypeOf(x).Align().As a special case, if a variable s is of struct type and f is a fieldwithin that struct, then Alignof(s.f) will return the required alignmentof a field of that type within a struct. This case is the same as thevalue returned byreflect.TypeOf(s.f).FieldAlign().The return value of Alignof is a Go constant if the type of the argumentdoes not have variable size.(See the description ofSizeof for a definition of variable sized types.)

funcOffsetof

func Offsetof(xArbitraryType)uintptr

Offsetof returns the offset within the struct of the field represented by x,which must be of the form structValue.field. In other words, it returns thenumber of bytes between the start of the struct and the start of the field.The return value of Offsetof is a Go constant if the type of the argument xdoes not have variable size.(See the description ofSizeof for a definition of variable sized types.)

funcSizeof

func Sizeof(xArbitraryType)uintptr

Sizeof takes an expression x of any type and returns the size in bytesof a hypothetical variable v as if v was declared via var v = x.The size does not include any memory possibly referenced by x.For instance, if x is a slice, Sizeof returns the size of the slicedescriptor, not the size of the memory referenced by the slice;if x is an interface, Sizeof returns the size of the interface value itself,not the size of the value stored in the interface.For a struct, the size includes any padding introduced by field alignment.The return value of Sizeof is a Go constant if the type of the argument xdoes not have variable size.(A type has variable size if it is a type parameter or if it is an arrayor struct type with elements of variable size).

funcStringadded ingo1.20

func String(ptr *byte, lenIntegerType)string

String returns a string value whose underlying bytesstart at ptr and whose length is len.

The len argument must be of integer type or an untyped constant.A constant len argument must be non-negative and representable by a value of type int;if it is an untyped constant it is given type int.At run time, if len is negative, or if ptr is nil and len is not zero,a run-time panic occurs.

Since Go strings are immutable, the bytes passed to Stringmust not be modified as long as the returned string value exists.

funcStringDataadded ingo1.20

func StringData(strstring) *byte

StringData returns a pointer to the underlying bytes of str.For an empty string the return value is unspecified, and may be nil.

Since Go strings are immutable, the bytes returned by StringDatamust not be modified.

Types

typeArbitraryType

type ArbitraryTypeint

ArbitraryType is here for the purposes of documentation only and is not actuallypart of the unsafe package. It represents the type of an arbitrary Go expression.

funcSliceadded ingo1.17

func Slice(ptr *ArbitraryType, lenIntegerType) []ArbitraryType

The function Slice returns a slice whose underlying array starts at ptrand whose length and capacity are len.Slice(ptr, len) is equivalent to

(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]

except that, as a special case, if ptr is nil and len is zero,Slice returns nil.

The len argument must be of integer type or an untyped constant.A constant len argument must be non-negative and representable by a value of type int;if it is an untyped constant it is given type int.At run time, if len is negative, or if ptr is nil and len is not zero,a run-time panic occurs.

funcSliceDataadded ingo1.20

func SliceData(slice []ArbitraryType) *ArbitraryType

SliceData returns a pointer to the underlying array of the argumentslice.

  • If cap(slice) > 0, SliceData returns &slice[:1][0].
  • If slice == nil, SliceData returns nil.
  • Otherwise, SliceData returns a non-nil pointer to anunspecified memory address.

typeIntegerTypeadded ingo1.17

type IntegerTypeint

IntegerType is here for the purposes of documentation only and is not actuallypart of the unsafe package. It represents any arbitrary integer type.

typePointer

type Pointer *ArbitraryType

Pointer represents a pointer to an arbitrary type. There are four special operationsavailable for type Pointer that are not available for other types:

  • A pointer value of any type can be converted to a Pointer.
  • A Pointer can be converted to a pointer value of any type.
  • A uintptr can be converted to a Pointer.
  • A Pointer can be converted to a uintptr.

Pointer therefore allows a program to defeat the type system and read and writearbitrary memory. It should be used with extreme care.

The following patterns involving Pointer are valid.Code not using these patterns is likely to be invalid todayor to become invalid in the future.Even the valid patterns below come with important caveats.

Running "go vet" can help find uses of Pointer that do not conform to these patterns,but silence from "go vet" is not a guarantee that the code is valid.

(1) Conversion of a *T1 to Pointer to *T2.

Provided that T2 is no larger than T1 and that the two share an equivalentmemory layout, this conversion allows reinterpreting data of one type asdata of another type. An example is the implementation ofmath.Float64bits:

func Float64bits(f float64) uint64 {return *(*uint64)(unsafe.Pointer(&f))}

(2) Conversion of a Pointer to a uintptr (but not back to Pointer).

Converting a Pointer to a uintptr produces the memory address of the valuepointed at, as an integer. The usual use for such a uintptr is to print it.

Conversion of a uintptr back to Pointer is not valid in general.

A uintptr is an integer, not a reference.Converting a Pointer to a uintptr creates an integer valuewith no pointer semantics.Even if a uintptr holds the address of some object,the garbage collector will not update that uintptr's valueif the object moves, nor will that uintptr keep the objectfrom being reclaimed.

The remaining patterns enumerate the only valid conversionsfrom uintptr to Pointer.

(3) Conversion of a Pointer to a uintptr and back, with arithmetic.

If p points into an allocated object, it can be advanced through the objectby conversion to uintptr, addition of an offset, and conversion back to Pointer.

p = unsafe.Pointer(uintptr(p) + offset)

The most common use of this pattern is to access fields in a structor elements of an array:

// equivalent to f := unsafe.Pointer(&s.f)f := unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f))// equivalent to e := unsafe.Pointer(&x[i])e := unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) + i*unsafe.Sizeof(x[0]))

It is valid both to add and to subtract offsets from a pointer in this way.It is also valid to use &^ to round pointers, usually for alignment.In all cases, the result must continue to point into the original allocated object.

Unlike in C, it is not valid to advance a pointer just beyond the end ofits original allocation:

// INVALID: end points outside allocated space.var s thingend = unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Sizeof(s))// INVALID: end points outside allocated space.b := make([]byte, n)end = unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(n))

Note that both conversions must appear in the same expression, with onlythe intervening arithmetic between them:

// INVALID: uintptr cannot be stored in variable// before conversion back to Pointer.u := uintptr(p)p = unsafe.Pointer(u + offset)

Note that the pointer must point into an allocated object, so it may not be nil.

// INVALID: conversion of nil pointeru := unsafe.Pointer(nil)p := unsafe.Pointer(uintptr(u) + offset)

(4) Conversion of a Pointer to a uintptr when calling functions likesyscall.Syscall.

The Syscall functions in package syscall pass their uintptr arguments directlyto the operating system, which then may, depending on the details of the call,reinterpret some of them as pointers.That is, the system call implementation is implicitly converting certain argumentsback from uintptr to pointer.

If a pointer argument must be converted to uintptr for use as an argument,that conversion must appear in the call expression itself:

syscall.Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(n))

The compiler handles a Pointer converted to a uintptr in the argument list ofa call to a function implemented in assembly by arranging that the referencedallocated object, if any, is retained and not moved until the call completes,even though from the types alone it would appear that the object is no longerneeded during the call.

For the compiler to recognize this pattern,the conversion must appear in the argument list:

// INVALID: uintptr cannot be stored in variable// before implicit conversion back to Pointer during system call.u := uintptr(unsafe.Pointer(p))syscall.Syscall(SYS_READ, uintptr(fd), u, uintptr(n))

(5) Conversion of the result ofreflect.Value.Pointer orreflect.Value.UnsafeAddrfrom uintptr to Pointer.

Package reflect's Value methods named Pointer and UnsafeAddr return type uintptrinstead of unsafe.Pointer to keep callers from changing the result to an arbitrarytype without first importing "unsafe". However, this means that the result isfragile and must be converted to Pointer immediately after making the call,in the same expression:

p := (*int)(unsafe.Pointer(reflect.ValueOf(new(int)).Pointer()))

As in the cases above, it is invalid to store the result before the conversion:

// INVALID: uintptr cannot be stored in variable// before conversion back to Pointer.u := reflect.ValueOf(new(int)).Pointer()p := (*int)(unsafe.Pointer(u))

(6) Conversion of areflect.SliceHeader orreflect.StringHeader Data field to or from Pointer.

As in the previous case, the reflect data structures SliceHeader and StringHeaderdeclare the field Data as a uintptr to keep callers from changing the result toan arbitrary type without first importing "unsafe". However, this means thatSliceHeader and StringHeader are only valid when interpreting the contentof an actual slice or string value.

var s stringhdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) // case 1hdr.Data = uintptr(unsafe.Pointer(p))              // case 6 (this case)hdr.Len = n

In this usage hdr.Data is really an alternate way to refer to the underlyingpointer in the string header, not a uintptr variable itself.

In general,reflect.SliceHeader andreflect.StringHeader should be usedonly as *reflect.SliceHeader and *reflect.StringHeader pointing at actualslices or strings, never as plain structs.A program should not declare or allocate variables of these struct types.

// INVALID: a directly-declared header will not hold Data as a reference.var hdr reflect.StringHeaderhdr.Data = uintptr(unsafe.Pointer(p))hdr.Len = ns := *(*string)(unsafe.Pointer(&hdr)) // p possibly already lost

funcAddadded ingo1.17

func Add(ptrPointer, lenIntegerType)Pointer

The function Add adds len to ptr and returns the updated pointerPointer(uintptr(ptr) + uintptr(len)).The len argument must be of integer type or an untyped constant.A constant len argument must be representable by a value of type int;if it is an untyped constant it is given type int.The rules for valid uses of Pointer still apply.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp