Source file test/typeparam/issue53087.go

     1  // run
     2  
     3  // Copyright 2022 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 I interface {
    12  	M()
    13  }
    14  
    15  type S struct {
    16  	str string
    17  }
    18  
    19  func (s *S) M() {}
    20  
    21  var _ I = &S{}
    22  
    23  type CloningMap[K comparable, V any] struct {
    24  	inner map[K]V
    25  }
    26  
    27  func (cm CloningMap[K, V]) With(key K, value V) CloningMap[K, V] {
    28  	result := CloneBad(cm.inner)
    29  	result[key] = value
    30  	return CloningMap[K, V]{result}
    31  }
    32  
    33  func CloneBad[M ~map[K]V, K comparable, V any](m M) M {
    34  	r := make(M, len(m))
    35  	for k, v := range m {
    36  		r[k] = v
    37  	}
    38  	return r
    39  }
    40  
    41  func main() {
    42  	s1 := &S{"one"}
    43  	s2 := &S{"two"}
    44  
    45  	m := CloningMap[string, I]{inner: make(map[string]I)}
    46  	m = m.With("a", s1)
    47  	m = m.With("b", s2)
    48  
    49  	it, found := m.inner["a"]
    50  	if !found {
    51  		panic("a not found")
    52  	}
    53  	if _, ok := it.(*S); !ok {
    54  		panic(fmt.Sprintf("got %T want *main.S", it))
    55  	}
    56  }
    57  

View as plain text