Home > Article > Backend Development > How to Resolve \'Mismatched Types: String and Byte\' Error in Golang?
The error in the provided Go code originates from the explicit conversion required when dealing with byte and string types. The error message, "invalid operation: new_str str[i 1] (mismatched types string and byte)," indicates that an attempt is being made to concatenate a string (new_str) with a byte (str[i 1]) from the underlying str array.
To resolve this issue, an explicit conversion must be applied to the byte type to convert it into a string. This can be achieved by using the string() function, as seen in the corrected code:
<code class="go">func g(str string) string { var i = 0 var new_str = "" for i < len(str)-1 { // Convert the byte to a string before concatenation new_str = new_str + string(str[i+1]) i = i + 1 } return new_str }</code>
By explicitly converting the byte to a string, the code adheres to Go's type system and successfully concatenates the strings without encountering the mismatched types error.
The above is the detailed content of How to Resolve \'Mismatched Types: String and Byte\' Error in Golang?. For more information, please follow other related articles on the PHP Chinese website!