about function argument type infer?

81 views
Skip to first unread message

xie cui

unread,
Mar 20, 2022, 7:20:06 AM3/20/22
to golang-nuts
package main

import (
        "fmt"
        "reflect"
)
import "golang.org/x/exp/constraints"
// Double returns a new slice that contains all the elements of s, doubled.
func Double[E constraints.Integer](s []E) []E {
        r := make([]E, len(s))
        for i, v := range s {
                r[i] = v
        }
        return r
}

func main() {
        // MySlice is a slice of ints.
        type MySlice []int

        // The type of V1 will be []int, not MySlice.
        // Here we are using function argument type inference,
        // but not constraint type inference.
        var V1 = Double(MySlice{1})
        fmt.Println(reflect.TypeOf(V1).String())
}

why use function argument type infer, and why function argument type infer int to []int?

Axel Wagner

unread,
Mar 20, 2022, 8:05:27 AM3/20/22
to xie cui, golang-nuts
On Sun, Mar 20, 2022 at 12:20 PM xie cui <cuiw...@gmail.com> wrote:
why use function argument type infer, and why function argument type infer int to []int?

Because the signature says `[]E`. So, the inference tries to determine `E`, infers it to be `int` and then substitutes that into the return type to make it `[]int`. `MySlice` is assignable to `[]int`, as they have the same underlying type and the latter is not a defined type. So, you can pass `MySlice` to `Double[int]` just fine.

You have to actually mention a separate type for the compiler to emit one, otherwise it will just do what it told you:
 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/f102326a-5cf6-40dc-bd57-268016284aecn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages