github.com/google/capslock@v0.2.3-0.20240517042941-dac19fc347c0/testpkgs/usegenerics/usegenerics.go (about)

     1  // Copyright 2023 Google LLC
     2  //
     3  // Use of this source code is governed by a BSD-style
     4  // license that can be found in the LICENSE file or at
     5  // https://developers.google.com/open-source/licenses/bsd
     6  
     7  // Package usegenerics is used for testing.
     8  package usegenerics
     9  
    10  import (
    11  	"net"
    12  	"os"
    13  	"sync/atomic"
    14  )
    15  
    16  type i interface {
    17  	Baz() int
    18  }
    19  
    20  type a int
    21  
    22  func (a a) Baz() int {
    23  	is, _ := net.Interfaces()
    24  	return 2 * int(a) * len(is)
    25  }
    26  
    27  // Foo is a generic function used for testing.
    28  func Foo[T i](a T, b int) int {
    29  	err := os.Rename("/tmp/12345", "/tmp/12345")
    30  	if err != nil {
    31  		b++
    32  	}
    33  	return a.Baz() + b
    34  }
    35  
    36  // Bar calls a generic function.
    37  func Bar() int {
    38  	var a a = 1
    39  	return Foo(a, 3)
    40  }
    41  
    42  // AtomicPointer calls various methods on an instantiation of the generic
    43  // type atomic.Pointer.
    44  func AtomicPointer() int {
    45  	i := 3
    46  	var x atomic.Pointer[int]
    47  	x.Store(&i)
    48  	x.Swap(&i)
    49  	x.CompareAndSwap(nil, nil)
    50  	return *x.Load()
    51  }
    52  
    53  // NestedFunction is a generic function that returns a nested function.
    54  func NestedFunction[T i](a T, b int) func() int {
    55  	return func() int { return a.Baz() + b }
    56  }
    57  
    58  // CallNestedFunction calls a function that is nested in a generic function.
    59  func CallNestedFunction() int {
    60  	var a a = 1
    61  	return NestedFunction(a, 3)() + 1
    62  }