Home >Backend Development >Golang >How to Fix \'invalid operation: new_str str[i 1] (mismatched types string and byte)\' in Golang?

How to Fix \'invalid operation: new_str str[i 1] (mismatched types string and byte)\' in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 13:38:30612browse

How to Fix

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:

  • In g, the concatenation of new_str and str[i 1] necessitates a type conversion. The correct syntax is new_str = new_str string(str[i 1]).
  • In f, the concatenation of f(g(str)) and str[0] also requires a type conversion. The corrected code is return f(g(str)) string(str[0]).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn