Tutorial Generic code - Code error

Just out of curiosity… I ran the code below which was a tutorial from https://go.dev/doc/tutorial/generics and I was getting error for unexpected comma , expected : for the the codes which call the generic functions.

Note:
* When the code is ran in the Go Playground, there is no issue.
* Yes I was running the beta they called for.
* This is not my code.

package main

import "fmt"

type Number interface {
    int64 | float64
}

func main() {
    // Initialize a map for the integer values
    ints := map[string]int64{
        "first": 34,
        "second": 12,
    }

    // Initialize a map for the float values
    floats := map[string]float64{
        "first": 35.98,
        "second": 26.99,
    }

    fmt.Printf("Non-Generic Sums: %v and %v\n",
        SumInts(ints),
        SumFloats(floats))

    fmt.Printf("Generic Sums: %v and %v\n",
        SumIntsOrFloats[string, int64](ints),
        SumIntsOrFloats[string, float64](floats))

    fmt.Printf("Generic Sums, type parameters inferred: %v and %v\n",
        SumIntsOrFloats(ints),
        SumIntsOrFloats(floats))

    fmt.Printf("Generic Sums with Constraint: %v and %v\n",
        SumNumbers(ints),
        SumNumbers(floats))
}

// SumInts adds together the values of m.
func SumInts(m map[string]int64) int64 {
    var s int64
    for _, v := range m {
        s += v
    }
    return s
}

// SumFloats adds together the values of m.
func SumFloats(m map[string]float64) float64 {
    var s float64
    for _, v := range m {
        s += v
    }
    return s
}

// SumIntsOrFloats sums the values of map m. It supports both floats and integers
// as map values.
func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {
    var s V
    for _, v := range m {
        s += v
    }
    return s
}

// SumNumbers sums the values of map m. Its supports both integers
// and floats as map values.
func SumNumbers[K comparable, V Number](m map[K]V) V {
    var s V
    for _, v := range m {
        s += v
    }
    return s
}

Can you please share the full error message as well as your go version?

I am running go1.18beta1 as per the instructions. I will have to get you the exact code later. I’m out at the moment.

The error which appears is

syntax error: unexpected comma, expecting :

The code was copied from the link above, and pasted into nano from a mac terminal. I’m curious if others receive the same error from copying and pasting it into a text editor rather than using the Go playground.

Works here… (run from Goland or via command line)…

Without any line numbers?

works here too, with go1.18beta1 and Goland

I copied and pasted this code in Golang plagroun and got error at
type Number interface {
int64 | float64 <— Here prog.go:6:11: expected ‘;’, found ‘|’ (and 5 more errors)
}

playground is at 1.17.6, not 1.18beta

yes.
You can switch playground to a “Go dev branch”

1 Like

I never noticed that before.