string - 如何在 Golang 中解决(字符串和字节类型不匹配)

标签 string go byte

func g(str string) string {
    var i = 0
    var new_str = ""
    for i < len(str) - 1 {
        new_str = new_str + str[i + 1]
        i = i + 1
}

func f(str string) string {
if len(str) == 0 {
    return ""
} else {
    if len(str) == 1 {
        return str
    } else {
        return f(g(str)) + str[0]
    }
}

func h(n uint64, str string) string {
for n != 1 {
    if n % 2 == 0 {
        n = n / 2
    } else {
        n = 3*n + 1
    }
    str = f(str)
}
return str
}


func pow(x, y uint64) uint64 {
if y == 0 {
    return 1
} else {
    return x * pow(x, y-1)
}
}


func main() {
fmt.Println(h(1, "fruits"))
fmt.Println(h(2, "fruits"))
fmt.Println(h(5, "fruits"))
fmt.Println(h(pow(2, 1000000000000000), "fruits"))
fmt.Println(h(pow(2, 1000000000000000), "fruits"))
}

command-line-arguments

.\fruits.go:11:21: invalid operation: new_str + str[i + 1] (mismatched types string and byte) .\fruits.go:24:21: invalid operation: f(g(str)) + str[0] (mismatched types string and byte)

最佳答案

错误消息描述了您的问题:无效操作:new_str + str[i + 1](字符串和字节类型不匹配)str[i + 1] 是底层 str 数组中的一个字节。 Go 需要显式转换。编写 string(str[i + 1])

例如,

package main

func g(str string) string {
    var i = 0
    var new_str = ""
    for i < len(str)-1 {

        // invalid operation: new_str + str[i + 1] (mismatched types string and byte)
        // new_str = new_str + str[i+1]

        new_str = new_str + string(str[i+1])
        i = i + 1
    }
    return new_str
}

func main() {}

Playground :https://play.golang.org/p/E9-n7IO-Q_z

关于string - 如何在 Golang 中解决(字符串和字节类型不匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51357928/

相关文章:

android - 在内存中加载大字符串的问题

go - rpc方法的定时器实现

arrays - 在 Go 中附加 2 维 slice

java - int[] 数组的outputStream.write()

Java 将 00010 打印为 8

java - 如何从文本字段获取值并将其保存在整数数组中,稍后将其显示在标签中

java - 不使用 Java Matcher 和 Pattern API 删除特殊字符

c# - ASP.NET:如果我的 sql 数据类型是 float,DataReader 的返回类型是什么?

bash - 如何使用 Go 在命令行上执行 diff?

java - 将字节数组加载到内存类加载器中