简体   繁体   English

在 golang 中将字符串转换为 *uint64

[英]Convert string to *uint64 in golang

Assume there is a string holding the address of an uint64 type variable, can we parse this address back to an *uint64 ?假设有一个字符串保存uint64类型变量的地址,我们可以将此地址解析回*uint64吗?

For example:例如:

i := uint64(23473824)
ip := &i
str := fmt.Sprintf("%v", ip)

u, _ := strconv.ParseUint(str, 0, 64)

u is uint64 . uuint64 How to get pointer out of this value?如何从这个值中取出指针?

Playground link: https://play.golang.org/p/1KXFQcozRk游乐场链接: https : //play.golang.org/p/1KXFQcozRk

It is as simple as:它很简单:

number, err := strconv.ParseUint(string("90"), 10, 64)

then do some error checking, hope it helps.然后做一些错误检查,希望它有帮助。

You can do it with你可以用

 ip = (*uint64)(unsafe.Pointer(uintptr(u)))

playground link游乐场链接

Albeit I don't know what guarantees Go gives you about the validity of such a pointer, nor can I think of any use case where this code should be used..尽管我不知道 Go 为您提供了关于此类指针有效性的什么保证,但我也想不出应该使用此代码的任何用例。

Based on nos answer .基于nos 答案

Although it is technically possible there are reasons not to trust the code you wrote.尽管在技术上是可能的,但有理由不信任您编写的代码。 Garbage collection will use the memory you point to (with string).垃圾收集将使用您指向的内存(带字符串)。

Take a look at result of the following code.看看下面代码的结果。

package main

import(
    "fmt"
    "strconv"
    "reflect"
    "unsafe"
)

func produce() string {
    i := uint64(23473824)
    ip := &i
    str := fmt.Sprintf("%v", ip)
    fmt.Println(i, ip, str)
    return str
}

func main() {
    str := produce()

    for i := 0; i < 10; i++ {
         x := make([]int, 1024*1024)
         x[0] = i
    }        

    u, _ := strconv.ParseUint(str, 0, 64) 

    ip := (*uint64)(unsafe.Pointer(uintptr(u)))
    fmt.Println(ip,*ip, reflect.TypeOf(u)) // u is uint64, how to get pointer out of this value?
}

https://play.golang.org/p/85XOhsMTf3 https://play.golang.org/p/85XOhsMTf3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM