Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
issue50002.go65 linesDownload Raw Back to typeparam
1// run2 3// Copyright 2021 The Go Authors. All rights reserved.4// Use of this source code is governed by a BSD-style5// license that can be found in the LICENSE file.6 7// Test for cases where certain instantiations of a generic function (F in this8// example) will always fail on a type assertion or mismatch on a type case.9 10package main11 12import "fmt"13 14type S struct{}15 16func (S) M() byte {17	return 018}19 20type I[T any] interface {21	M() T22}23 24func F[T, A any](x I[T], shouldMatch bool) {25	switch x.(type) {26	case A:27		if !shouldMatch {28			fmt.Printf("wanted mis-match, got match")29		}30	default:31		if shouldMatch {32			fmt.Printf("wanted match, got mismatch")33		}34	}35 36	_, ok := x.(A)37	if ok != shouldMatch {38		fmt.Printf("ok: got %v, wanted %v", ok, shouldMatch)39	}40 41	if !shouldMatch {42		defer func() {43			if shouldMatch {44				fmt.Printf("Shouldn't have panicked")45			}46			recover()47		}()48	}49	_ = x.(A)50	if !shouldMatch {51		fmt.Printf("Should have panicked")52	}53}54 55func main() {56	// Test instantiation where the type switch/type asserts can't possibly succeed57	// (since string does not implement I[byte]).58	F[byte, string](S{}, false)59 60	// Test instantiation where the type switch/type asserts should succeed61	// (since S does implement I[byte])62	F[byte, S](S{}, true)63	F[byte, S](I[byte](S{}), true)64}65 
codekingpro/portable-devtools · Team Ai