test/gen: add some FromStrings test cases

These are from the latest version of the design draft.

There are still a couple of FromStrings test cases that don't yet work.

Change-Id: I057875820d8250012c06faeabda4637f0585b6f8
Reviewed-on: https://team-review.git.corp.google.com/c/golang/go2-dev/+/763941
Reviewed-by: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Ian Lance Taylor 2020-06-05 10:03:44 -07:00 committed by Robert Griesemer
parent a6b6ca6dc9
commit 35eefe6b79
3 changed files with 122 additions and 0 deletions

41
test/gen/g008.go2 Normal file
View File

@ -0,0 +1,41 @@
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
type Setter interface {
Set(string)
}
func FromStrings(type T Setter)(s []string) []T {
result := make([]T, len(s))
for i, v := range s {
result[i].Set(v)
}
return result
}
type Settable int
func (p *Settable) Set(s string) {
*p = 0
}
func F() {
defer func() {
if recover() == nil {
panic("did not panic as expected")
}
}()
// This should type check but should panic at run time,
// because it will make a slice of *Settable and then call
// Set on a nil value.
FromStrings(*Settable)([]string{"1"})
}
func main() {
F()
}

43
test/gen/g009.go2 Normal file
View File

@ -0,0 +1,43 @@
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"log"
"strconv"
)
type Setter2(type B) interface {
Set(string)
type *B
}
func FromStrings2(type T interface{}, PT Setter2(T))(s []string) []T {
result := make([]T, len(s))
for i, v := range s {
p := PT(&result[i])
p.Set(v)
}
return result
}
type Settable int
func (p *Settable) Set(s string) {
i, err := strconv.Atoi(s)
if err != nil {
log.Fatal(err)
}
*p = Settable(i)
}
func main() {
s := FromStrings2(Settable, *Settable)([]string{"1"})
if len(s) != 1 || s[0] != 1 {
log.Fatalf("got %v, want %v", s, []int{1})
}
}

38
test/gen/g010.go2 Normal file
View File

@ -0,0 +1,38 @@
// run
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"log"
"strconv"
)
func FromStrings3(type T)(s []string, set func(*T, string)) []T {
results := make([]T, len(s))
for i, v := range s {
set(&results[i], v)
}
return results
}
type Settable int
func (p *Settable) Set(s string) {
i, err := strconv.Atoi(s)
if err != nil {
log.Fatal(err)
}
*p = Settable(i)
}
func main() {
s := FromStrings3(Settable)([]string{"1"},
func(p *Settable, s string) { p.Set(s) })
if len(s) != 1 || s[0] != 1 {
log.Fatalf("got %v, want %v", s, []int{1})
}
}