pointer_helpers.go raw

   1  package linodego
   2  
   3  /*
   4  Pointer takes a value of any type T and returns a pointer to that value.
   5  Go does not allow directly creating pointers to literals, so Pointer enables
   6  abstraction away the pointer logic.
   7  
   8  Example:
   9  
  10  		booted := true
  11  
  12  		createOpts := linodego.InstanceCreateOptions{
  13  			Booted: &booted,
  14  		}
  15  
  16  		can be replaced with
  17  
  18  		createOpts := linodego.InstanceCreateOptions{
  19  			Booted: linodego.Pointer(true),
  20  		}
  21  */
  22  
  23  func Pointer[T any](value T) *T {
  24  	return &value
  25  }
  26  
  27  // DoublePointer creates a double pointer to a value of type T.
  28  //
  29  // This is useful for APIs that distinguish between null and omitted fields.
  30  //
  31  // Example:
  32  //
  33  //	// For a field that should be non-null value in the API payload:
  34  //	value := linodego.DoublePointer(42) // Returns **int pointing a *int pointer pointing to 42
  35  //
  36  //	// For a field that should be null in the API payload, use `DoublePointerNull` function instead:
  37  //	nullValue := linodego.DoublePointerNull[int]() // Returns **int that is nil
  38  //
  39  //	// For a field that should not be included in the API payload, simply not include it in the struct.
  40  func DoublePointer[T any](value T) **T {
  41  	valuePtr := &value
  42  	return &valuePtr
  43  }
  44  
  45  // DoublePointerNull creates a double pointer pointing to a nil pointer of type T,
  46  // indicating that the field should be null in the API payload.
  47  //
  48  // This is useful for APIs that distinguish between null and omitted fields.
  49  func DoublePointerNull[T any]() **T {
  50  	return Pointer[*T](nil)
  51  }
  52