Skip to content

Go Language

Go Type System and Type Conversion

A Failure of Assignment

Recently, my friend asked me a question, why inthe following go code, b cannot be assigned to f? With knowledges about AST, I got intrigue on it than ever before.

type (
    Bar string
    Foo Bar
)

func main() {
    var f Foo
    var b Bar
    f = b
}
/main.go:17:6: cannot use b (variable of type Bar) as type Foo in assignment
func main() {
    var f Foo = "foo"
    var b Bar
}

The failure is caused by Bar and Foo are not same type, hence, they cannot be assigned to each other. However, assign a string to Bar or Foo directly is valid.

This blog talks why the conversion fails and will introduce the type, type definition, properities of types with some examples.

Precise Lose Between Float64 and Uint64

In astjson library, the lexer scans the number and stores the respective bytes. Then the parser will parse the bytes to number which is expressed by a float64. It works well at beginning, however, once I added a corner case of number with value math.MaxUint64(1<<64 - 1 or decimal value 18446744073709551615), the parser cannot work as expected. It's indeed a bug issue.

The simplified problem is the value through debug of f is 18446744073709552000 instead of 18446744073709551615.

f, _ = strconv.ParseFloat("18446744073709551615", 64)

Developing Notes of ASTJSON Library

After reading about the compiler, I feel intrigued as it challenges me with numerous design and implementation details. It's an exciting topic for me. Inspired by the APIs the Haskell Aeson library exposed, it's a good practice for me to write a toy library named xieyuschen/astjson to parse JSON string to AST in a slightly functional way. This is a developing notes page, and I record some reflections.