title: Go语言解决:无法将 'i.Value' (类型 interface{}) 用作类型 string
date: 2022-01-21 00:42:24.0
updated: 2022-01-21 00:48:04.0
url: https://liumou.site/doc/239
categories:

  • GO

    tags:

被调用函数

func netcheck(ip string, port string) bool {
    // 检测网络连接状态
    // urls 传入一个访问URL
    urls := ip + port
    fmt.Println(urls)
    timeout := time.Duration(1 * time.Second)
    _, err := net.DialTimeout("tcp",urls, timeout)
    if err != nil {
        log.Println("Site unreachable, error: ", err)
        return false
    }
    fmt.Println("连接成功")
    return true

}

调用函数

func Network(net_type string) (bool, string) {
    fmt.Println("已进入网络检测步骤...")
    // 检测网络连接状态,当前函数负责传送服务器信息
    ipList := list.New() //创建一个新列表
    // 向列表插入元素,字符串类型必须使用双引号
    if string(net_type) == string("z") {
        fmt.Println("优先检测zw环境")
        ipList.PushFront("10.18.26.2")
        ipList.PushBack("116.1.203.133")
    } else {
        fmt.Println("优先检测外网环境")
        ipList.PushFront("10.18.26.1")
    }
    for i := ipList.Front(); i != nil; i = i.Next() { //开始进行遍历,从头部开始,只要i不等于空就一直下一步
        if i.Value == string("116.1.203.133") {
            fmt.Println(i.Value)
            status := netcheck("116.1.203.133", ":8224")
            fmt.Println(status)
            if status == true{
                return true, "116.1.203.133"
            }
        }else {
            fmt.Println(i.Value) //打印每次遍历的i值
            status := netcheck(i.Value, ":81")
            if status == true{
                return true, fmt.Sprint(i.Value)
            }
        }
    }
    return false, "连接错误"
}

当使用i.Value去赋值的时候,会出现错误提示:

无法将 'i.Value' (类型 interface{}) 用作类型 string

这是因为通过Value得到的数据并不是字符串数据,所以需要先使用fmt去转换成字符串数据才能被函数接收,这是因为在Go语言中,类型都是强制的,属于一种强类型语言,无法像python那样随意传入任意类型的数据

正确的调用方法

使用fmt.Sprint(i.Value)处理数据

func Network(net_type string) (bool, string) {
    fmt.Println("已进入网络检测步骤...")
    // 检测网络连接状态,当前函数负责传送服务器信息
    ipList := list.New() //创建一个新列表
    // 向列表插入元素,字符串类型必须使用双引号
    if string(net_type) == string("z") {
        fmt.Println("优先检测zw环境")
        ipList.PushFront("10.18.26.2")
        ipList.PushBack("116.1.203.133")
    } else {
        fmt.Println("优先检测外网环境")
        ipList.PushFront("10.18.26.1")
    }
    for i := ipList.Front(); i != nil; i = i.Next() { //开始进行遍历,从头部开始,只要i不等于空就一直下一步
        if i.Value == string("116.1.203.133") {
            fmt.Println(i.Value)
            status := netcheck("116.1.203.133", ":8224")
            fmt.Println(status)
            if status == true{
                return true, "116.1.203.133"
            }
        }else {
            fmt.Println(i.Value) //打印每次遍历的i值
            status := netcheck(fmt.Sprint(i.Value), ":81")
            if status == true{
                return true, fmt.Sprint(i.Value)
            }
        }
    }
    return false, "连接错误"
}

具体用法请参考

菜鸟教程