Delete a set variable or change it's type

package main
import "fmt"
func main() {
        a := "hello"
        fmt.Println(a)
        a = 123
        fmt.Println(a)
}

This gives the error

cannot use 123 (type int) as type string in assignment

How do I reuse varible a with another type of value or if possible delete the varible and then re-declare the variable of new type?

afaik, it’s impossible.Even if no type appears in the assignment/declaration of a , it’s as if you wrote this : https://play.golang.org/p/JWj-ajWFrcK
Even if underground, strong typing is at work.

As go is blockscoped you can use blocks to limit the scope of a:

package main

import "fmt"

func main() {
	{
		a := "hello"
		fmt.Println(a)
	}
	{
		a := 123
		fmt.Println(a)
	}
}

But in my opinion, its better to use separate variables. Just use a and b

3 Likes

go is a typed language. Thus you cannot assign different types to the same variable like in Python or Javascript. You have to use blocks to separate the variables or use different variable names.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.