Source file test/typeparam/issue52026.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  func returnOption[T any](n int) Option[T] {
    10  	if n == 1 {
    11  		return Some[T]{}
    12  	} else {
    13  		return None{}
    14  	}
    15  }
    16  
    17  type Option[T any] interface {
    18  	sealedOption()
    19  }
    20  
    21  type Some[T any] struct {
    22  	val T
    23  }
    24  
    25  func (s Some[T]) Value() T {
    26  	return s.val
    27  }
    28  
    29  func (s Some[T]) sealedOption() {}
    30  
    31  type None struct{}
    32  
    33  func (s None) sealedOption() {}
    34  
    35  func main() {
    36  	s := returnOption[int](1)
    37  	_ = s.(Some[int])
    38  
    39  	s = returnOption[int](0)
    40  	_ = s.(None)
    41  
    42  	switch (any)(s).(type) {
    43  	case Some[int]:
    44  		panic("s is a Some[int]")
    45  	case None:
    46  		// ok
    47  	default:
    48  		panic("oops")
    49  	}
    50  }
    51  

View as plain text