[generics] Type parameter inference in generic struct literals

86 views
Skip to first unread message

to...@sourcegraph.com

unread,
Jun 17, 2020, 12:36:02 PM6/17/20
to golang-nuts
Hello all,

Could type parameters be omitted when they could be inferred in struct literals? 

Here's a scenario that doesn't work today (https://go2goplay.golang.org/p/Jt5OGfLePuu)
package main

import (
"fmt"
)

type BinaryTree(type T) struct {
Value       T
Left, Right *BinaryTree(T)
}

func main() {
n := int(42)
tree := BinaryTree{
Value: n,
Left:  {Value: n - 1},
Right: {Value: n + 1},
}

fmt.Println(tree)
}

Instead we must be explicit at every struct literal instantiation which quickly becomes quite cluttered (https://go2goplay.golang.org/p/vi6GM4AxyV_r):

package main

import (
"fmt"
)

type BinaryTree(type T) struct {
Value       T
Left, Right *BinaryTree(T)
}

func main() {
n := int(42)
tree := BinaryTree(int) {
Value: n,
Left:  &BinaryTree(int){Value: n - 1},
Right: &BinaryTree(int){Value: n + 1},
}

fmt.Println(tree)
}





Ian Lance Taylor

unread,
Jun 17, 2020, 8:43:35 PM6/17/20
to to...@sourcegraph.com, golang-nuts
On Wed, Jun 17, 2020 at 9:35 AM tomas via golang-nuts
<golan...@googlegroups.com> wrote:
>
> Could type parameters be omitted when they could be inferred in struct literals?

https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#type-inference-for-composite-literals

Ian
Reply all
Reply to author
Forward
0 new messages