Home >Backend Development >Golang >How to Fix \'invalid operation: new_str str[i 1] (mismatched types string and byte)\' in Golang?
Type Mismatch in Golang: Resolving the Error (mismatched types string and byte)
In Golang, you may encounter the error "invalid operation: new_str str[i 1] (mismatched types string and byte)" due to type mismatch. This error arises when attempting to concatenate a byte (str[i 1]) with a string (new_str). Go mandates explicit type conversions.
In the example code provided, this error occurs in the g and f functions:
By explicitly converting bytes to strings, you can resolve the type mismatch and avoid the error. Here's a revised code snippet with the necessary conversions:
<code class="go">package main func g(str string) string { var i = 0 var new_str = "" for i < len(str)-1 { new_str = new_str + string(str[i+1]) i = i + 1 } return new_str } func f(str string) string { if len(str) == 0 { return "" } else if len(str) == 1 { return str } else { return f(g(str)) + string(str[0]) } } func main() { // ... }</code>
The above is the detailed content of How to Fix \'invalid operation: new_str str[i 1] (mismatched types string and byte)\' in Golang?. For more information, please follow other related articles on the PHP Chinese website!