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


given 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 employee")     }      fmt.println(string(b)) } 

can checking error reliably ignored using _ placeholder since employee struct defined. theoretically should never fail, begs question practice ignore type of error , save little on type of boilerplate error checking?

ignoring 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)) } 

error handling , go:

proper error handling essential requirement of software.


normally code won't fail. if user adds marshaljson method reciver type, fails:

func (t *employee) marshaljson() ([]byte, error) {     if t.id == 2 {         return nil, fmt.errorf("forbiden id = %d", t.id)     }     data := []byte(fmt.sprintf(`{"id":%d}`, t.id))     return data, nil } 

this code compiles, fails on purpose id == 2 (the go playground):

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 employee", err)     }      fmt.println(string(b)) }  func (t *employee) marshaljson() ([]byte, error) {     if t.id == 2 {         return nil, fmt.errorf("forbiden id = %d", t.id)     }     data := []byte(fmt.sprintf(`{"id":%d}`, t.id))     return data, nil } 

also code compiles, fails (the go playground):

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 employee")     }      fmt.println(string(b)) }  func (t employee) marshaljson() ([]byte, error) {     data := []byte(fmt.sprint(t))     return data, nil } 


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -