Home > OS >  How to declare and use a variable which can store both string and int values in Go?
How to declare and use a variable which can store both string and int values in Go?

Time:02-12

I've the following struct:

type testCase struct {
   input   string
   isValid bool
}

I want to use this struct in multiple tests and input could be either a string or an intetc.
I can convert the int input to string and convert it back to int while processing, or I can define two different structs e.g. testCaseInt and testCaseStruct which will solve my problem but how do I solve this by converting input to an interface?

I'm new to Go and tried Googling about this but couldn't find maybe because I don't know what to search for.

CodePudding user response:

How to declare and use a variable which can store both string and int values in Go?

You cannot. Go's type system (as of Go 1.17) doesn't provide sum types.

You will have to wait for Go 1.18.

CodePudding user response:

Method 1:

package main

import (
    "fmt"
)

func main() {
    var a interface{}
    a = "hi"
    if valString, ok := a.(string); ok {
        fmt.Printf("String: %s", valString)
    }
    a = 1
    if valInt, ok := a.(int); ok {
        fmt.Printf("\nInteger: %d", valInt)
    }
}

Method 2:

package main

import (
    "fmt"
)

func main() {
    print("hi")
    print(1)
}

func print(a interface{}) {
    switch t := a.(type) {
    case int:
        fmt.Printf("Integer: %v\n", t)
    case string:
        fmt.Printf("String: %v\n", t)
    }
}
  • Related