Help us shape the future of Go! Take the 2026 Go Developer Survey

allocate

package module
v0.0.0-...-986f24f Latest Latest
Warning

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

Go to latest
Published: May 10, 2022 License: MIT Imports: 2 Imported by: 7

README

Allocate

Build Status Coverage Status Go Report Card MIT licensed GoDoc

Allocate provides functions for allocating golang structs so that pointer fields are pointers to zero'd values instead of nil. See the godoc's for more information: https://godoc.org/github.com/cjrd/allocate

Brief Example

package main

import (
    "fmt"
    "github.com/cjrd/allocate"
)

type TopLevelStruct struct {
    MyEmbeddedStruct *EmbeddedStruct
}

type EmbeddedStruct struct {
    SomeString string
    SomeInt int
}

func main() {
    topStruct := new(TopLevelStruct)
    fmt.Printf("before using allocate.Zero: %v\n", topStruct)

    allocate.Zero(&topStruct)
    fmt.Printf("post allocate.Zero: %v\n", topStruct)
    fmt.Printf("topStruct.MyEmbeddedStruct.SomeInt==%d\n", topStruct.MyEmbeddedStruct.SomeInt)
    // Note that panics would occur by executing `*topStruct.MyEmbeddedStruct` or
    //`topStruct.MyEmbeddedStruct.SomeInt`
}
# OUTPUT
before using allocate.Zero: &{<nil>}
post allocate.Zero: &{0x8201d2400}
topStruct.MyEmbeddedStruct.SomeInt == 0

Use Cases

  • Initializing structures that contain any type of pointer fields, including recursive struct fields
  • Preventing panics by ensuring that all fields of a struct are initialized
  • Initializing golang protobuf struct (the golang protobuf makes heavy use of pointers to embedded structs that contain pointers to embedded structs, ad infinitum)
  • Initializing structs for black box testing (see also https://golang.org/pkg/testing/quick/)

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustZero

func MustZero(inputIntf interface{})

MustZero will panic instead of return error

func Zero

func Zero(inputIntf interface{}) error

Zero allocates an input structure such that all pointer fields are fully allocated, i.e. rather than having a nil value, the pointer contains a pointer to an initialized value, e.g. an *int field will be a pointer to 0 instead of a nil pointer.

Zero does not allocate private fields.

Example

ExampleZero is a simple example to demonstrate the how Zero() performs allocation

type SimplePtrStruct struct {
	PtrField *int
}

ptrStruct := SimplePtrStruct{}

fmt.Printf("pre allocate.Zero: %v\n", ptrStruct.PtrField)
Zero(&ptrStruct)
fmt.Printf("post allocate.Zero: %v\n", *ptrStruct.PtrField)
Output:
pre allocate.Zero: <nil>
post allocate.Zero: 0

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL