Delete a set variable or change it's type


(Rahul Bansal) #1
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?


(Ivan Matmati) #2

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.


(Norbert Melzer) #3

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


(framp) #4

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.


(system) closed #5

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