Source file test/typeparam/issue47925d.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  type I[T any] interface {
    10  	foo()
    11  }
    12  
    13  type J[T any] interface {
    14  	foo()
    15  	bar()
    16  }
    17  
    18  //go:noinline
    19  func f[T J[T]](x T, g func(T) T) I[T] {
    20  	// contains a cast between two nonempty interfaces
    21  	// Also make sure we don't evaluate g(x) twice.
    22  	return I[T](J[T](g(x)))
    23  }
    24  
    25  type S struct {
    26  	x int
    27  }
    28  
    29  func (s *S) foo() {}
    30  func (s *S) bar() {}
    31  
    32  var cnt int
    33  
    34  func inc(s *S) *S {
    35  	cnt++
    36  	return s
    37  }
    38  
    39  func main() {
    40  	i := f(&S{x: 7}, inc)
    41  	if i.(*S).x != 7 {
    42  		panic("bad")
    43  	}
    44  	if cnt != 1 {
    45  		panic("multiple calls")
    46  	}
    47  }
    48  

View as plain text