Source file test/typeparam/double.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 (
    10  	"fmt"
    11  	"reflect"
    12  )
    13  
    14  type Number interface {
    15  	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64
    16  }
    17  
    18  type MySlice []int
    19  type MyFloatSlice []float64
    20  
    21  type _SliceOf[E any] interface {
    22  	~[]E
    23  }
    24  
    25  func _DoubleElems[S _SliceOf[E], E Number](s S) S {
    26  	r := make(S, len(s))
    27  	for i, v := range s {
    28  		r[i] = v + v
    29  	}
    30  	return r
    31  }
    32  
    33  // Test use of untyped constant in an expression with a generically-typed parameter
    34  func _DoubleElems2[S _SliceOf[E], E Number](s S) S {
    35  	r := make(S, len(s))
    36  	for i, v := range s {
    37  		r[i] = v * 2
    38  	}
    39  	return r
    40  }
    41  
    42  func main() {
    43  	arg := MySlice{1, 2, 3}
    44  	want := MySlice{2, 4, 6}
    45  	got := _DoubleElems[MySlice, int](arg)
    46  	if !reflect.DeepEqual(got, want) {
    47  		panic(fmt.Sprintf("got %s, want %s", got, want))
    48  	}
    49  
    50  	// constraint type inference
    51  	got = _DoubleElems[MySlice](arg)
    52  	if !reflect.DeepEqual(got, want) {
    53  		panic(fmt.Sprintf("got %s, want %s", got, want))
    54  	}
    55  
    56  	got = _DoubleElems(arg)
    57  	if !reflect.DeepEqual(got, want) {
    58  		panic(fmt.Sprintf("got %s, want %s", got, want))
    59  	}
    60  
    61  	farg := MyFloatSlice{1.2, 2.0, 3.5}
    62  	fwant := MyFloatSlice{2.4, 4.0, 7.0}
    63  	fgot := _DoubleElems(farg)
    64  	if !reflect.DeepEqual(fgot, fwant) {
    65  		panic(fmt.Sprintf("got %s, want %s", fgot, fwant))
    66  	}
    67  
    68  	fgot = _DoubleElems2(farg)
    69  	if !reflect.DeepEqual(fgot, fwant) {
    70  		panic(fmt.Sprintf("got %s, want %s", fgot, fwant))
    71  	}
    72  }
    73  

View as plain text