Golang DeReference 指针作为接口传递给方法{}

问题描述 投票:0回答:2

示例:

import (
   "fmt"
)

func main() {
   var v = ""
   fmt.Println(isEmptyString(&v))
}

func isEmptyString(val interface{}) bool {
   // lets say we know it is string and don't need to check
   // how to dereference val into string value so we can do value == "" ????

}

正常的 deRef * 不起作用,尝试使用反射包..没有运气

go pointers
2个回答
0
投票

您需要的代码是这样的:

package main

import (
    "fmt"
)

func main() {
    var v = ""
    fmt.Println(isEmptyString(&v))
}

func isEmptyString(val interface{}) (bool, error) {
    switch v := val.(type) {
    case *string:
        str := *v
        if str == "" {

            return true, nil

        }
        return false, nil
    default:
        return false, fmt.Errorf("the value is not string pointer")
    }
}

0
投票

既然你说你知道它是字符串并且不需要检查,你可以这样:

import (
    "fmt"
)

func main() {
    var v = ""
    fmt.Println(isEmptyString(&v))
}

func isEmptyString(val interface{}) bool {
    return *val.(*string) == ""
}
© www.soinside.com 2019 - 2024. All rights reserved.