Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, can JSON marshaling of a well-defined type ever fail?

Tags:

Given the following code:

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Employee struct {
    Id int "json:id"
}

func main() {
    b, err := json.Marshal(&Employee{Id: 2})
    if err != nil {
        log.Fatal("Couldn't marshal the Employee")
    }

    fmt.Println(string(b))
}

Can checking for the error be reliably ignored using the _ placeholder since the Employee struct is well defined. Theoretically it should never fail, so begs the question is it a good practice to ignore this type of error and save a little on this type of boilerplate error checking?

Ignoring would look like so:

package main

import (
    "encoding/json"
    "fmt"
)

type Employee struct {
    Id int "json:id"
}

func main() {
    b, _ := json.Marshal(&Employee{Id: 2})
    fmt.Println(string(b))
}