{"id":317,"hash":"e01b033a61f2bbd400902e7080c0883486befb9e1d9ff055845a6fe5734d0b36","pattern":"cannot convert data (type interface {}) to type string: need type assertion","full_message":"I am pretty new to go and I was playing with this notify package.\n\nAt first I had code that looked like this:\n\nfunc doit(w http.ResponseWriter, r *http.Request) {\n    notify.Post(\"my_event\", \"Hello World!\")\n    fmt.Fprint(w, \"+OK\")\n}\n\nI wanted to append newline to Hello World! but not in the function doit above, because that would be pretty trivial, but in the handler afterwards like this below:\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    myEventChan := make(chan interface{})\n    notify.Start(\"my_event\", myEventChan)\n    data := <-myEventChan\n    fmt.Fprint(w, data + \"\\n\")\n}\n\nAfter go run:\n\n$ go run lp.go \n# command-line-arguments\n./lp.go:15: invalid operation: data + \"\\n\" (mismatched types interface {} and string)\n\nAfter a little bit of Googling I found this question on SO.\n\nThen I updated my code to:\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n    myEventChan := make(chan interface{})\n    notify.Start(\"my_event\", myEventChan)\n    data := <-myEventChan\n    s:= data.(string) + \"\\n\"\n    fmt.Fprint(w, s)\n}\n\nIs this what I was supposed to do? My compiler errors are gone so I guess that's pretty good? Is this efficient? Should you do it differently?","ecosystem":"go","package_name":"type-mismatch","package_version":null,"solution":"According to the Go specification:\n\n  For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.\n\nA \"type assertion\" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.\n\nIn your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.\n\nIf you were unsure if it was a string or not, you could test using the two return syntax.\n\nstr, ok := data.(string)\n\nIf data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:\n\nif str, ok := data.(string); ok {\n    /* act on str */\n} else {\n    /* not string */\n}","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/14289256/cannot-convert-data-type-interface-to-type-string-need-type-assertion","votes":279,"created_at":"2026-04-19T04:41:52.371291+00:00","updated_at":"2026-04-19T04:52:38.787789+00:00"}