LoginSignup
0
0

More than 5 years have passed since last update.

fmt.Printf with struct field without names.

Last updated at Posted at 2018-04-23

Test code ( https://play.golang.org/p/z__pwPlGxAT ):

package main

import (
    "fmt"
)


func test(i interface{}){
    switch i.(type) {
    case error:
        fmt.Printf("error type\n")
    default:
        fmt.Printf("other type\n")
    }
    fmt.Printf("%v\n", i)
}

func main() {

    i1 := struct {
        string
        error
    }{ "a", nil }

    fmt.Println("--------- case 1 ---------")
    test(i1)

    i2 := struct {
        S string
        error
    }{ "a", nil }

    fmt.Println("--------- case 2 ---------")
    test(i2)

    i3 := struct {
        string
        E error
    }{ "a", nil }

    fmt.Println("--------- case 3 ---------")
    test(i3)

}

Output:

--------- case 1 ---------
error type
%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)
--------- case 2 ---------
error type
%!v(PANIC=runtime error: invalid memory address or nil pointer dereference)
--------- case 3 ---------
other type
{a <nil>}

Conclusion

If an anonymous struct with a error field but without give the field a name, the Printf('%v') will process this struct as an error type, but the error field is nil, Printf will call error.Error() to print its value, so we got an runtime error: invalid memory address or nil pointer dereference error message.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0