function - 如何转换函数类型?

标签 function go

<分区>

我想在 expend 中使用 upCase 作为变量,但它说“不能将‘upCase(s1)’(type string)用作 type func(string) string。 我怎样才能转换 upCase 类型?或者我需要做什么才能使错误消失?

package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "test func"
    s1 := ""
    test := expand(s, upCase(s1))
    fmt.Print(test)
}
func expand(s string, f func(string) string) string {
    s1 := "test"
    var s2 string
    if strings.Contains(s, s1) {
        // todo 字符串中s1的值更改为f(s1)的值
        s1 = f(s1)
        strings.Replace(s1, s, s2, -1)
    } else {
        return ""
    }
    return s2
}

func upCase(s string) string {
    s = strings.ToUpper(s)
    return s
}

最佳答案

您在对 expand 的调用中调用了 upCase 函数(因此它返回一个您传递给 expand 函数的字符串)。你需要传入函数:

test := expand(s, upCase)

您当前的代码 test := expand(s, upCase(s1)) 与以下操作相同:

v := upCase(s1)
test := expand(s, v)

即,您只是调用 upCase(s1) 返回一个字符串,然后将该字符串传递给 expand ,它需要一个函数,而不是一个字符串作为它的2.论证。

关于function - 如何转换函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51962013/

相关文章:

php - 在类内部使用php pack()函数时出现语法错误

Golang 错误和文档

time - 在不受时钟变化影响的情况下对操作进行计时

memory - 如何在 golang 中以字节为单位获取结构的大小及其内容?

postgresql - 具有嵌套 IF 的 Postgres 函数

bash - 导出不工作(从一个函数调用以获取其回显)

javascript函数返回值未按预期工作

JavaScript : Split string using function and returning it

http - 如何在 GO 中获取 LocalAddress?

go - 基本 goroutine 和 channel 模式 : multiple goroutines for one channel