Source file test/typeparam/value.go

     1  // run
     2  
     3  // Copyright 2021 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import "fmt"
    10  
    11  type value[T any] struct {
    12  	val T
    13  }
    14  
    15  func get[T any](v *value[T]) T {
    16  	return v.val
    17  }
    18  
    19  func set[T any](v *value[T], val T) {
    20  	v.val = val
    21  }
    22  
    23  func (v *value[T]) set(val T) {
    24  	v.val = val
    25  }
    26  
    27  func (v *value[T]) get() T {
    28  	return v.val
    29  }
    30  
    31  func main() {
    32  	var v1 value[int]
    33  	set(&v1, 1)
    34  	if got, want := get(&v1), 1; got != want {
    35  		panic(fmt.Sprintf("get() == %d, want %d", got, want))
    36  	}
    37  
    38  	v1.set(2)
    39  	if got, want := v1.get(), 2; got != want {
    40  		panic(fmt.Sprintf("get() == %d, want %d", got, want))
    41  	}
    42  
    43  	v1p := new(value[int])
    44  	set(v1p, 3)
    45  	if got, want := get(v1p), 3; got != want {
    46  		panic(fmt.Sprintf("get() == %d, want %d", got, want))
    47  	}
    48  
    49  	v1p.set(4)
    50  	if got, want := v1p.get(), 4; got != want {
    51  		panic(fmt.Sprintf("get() == %d, want %d", got, want))
    52  	}
    53  
    54  	var v2 value[string]
    55  	set(&v2, "a")
    56  	if got, want := get(&v2), "a"; got != want {
    57  		panic(fmt.Sprintf("get() == %q, want %q", got, want))
    58  	}
    59  
    60  	v2.set("b")
    61  	if got, want := get(&v2), "b"; got != want {
    62  		panic(fmt.Sprintf("get() == %q, want %q", got, want))
    63  	}
    64  
    65  	v2p := new(value[string])
    66  	set(v2p, "c")
    67  	if got, want := get(v2p), "c"; got != want {
    68  		panic(fmt.Sprintf("get() == %d, want %d", got, want))
    69  	}
    70  
    71  	v2p.set("d")
    72  	if got, want := v2p.get(), "d"; got != want {
    73  		panic(fmt.Sprintf("get() == %d, want %d", got, want))
    74  	}
    75  }
    76  

View as plain text