Convert string to *uint64 in golang

huangapple go评论83阅读模式
英文:

Convert string to *uint64 in golang

问题

假设有一个字符串保存了一个 uint64 类型变量的地址,我们能将这个地址解析回 *uint64 类型吗?

例如:

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

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

uuint64 类型。如何从这个值中获取指针?

Playground 链接:https://play.golang.org/p/1KXFQcozRk

英文:

Assume there is a string holding the address of an uint64 type variable, can we parse this address back to an *uint64?

For example:

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

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

u is uint64. How to get pointer out of this value?

Playground link: https://play.golang.org/p/1KXFQcozRk

答案1

得分: 17

这是一个简单的示例:

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

然后进行一些错误检查,希望对你有帮助。

英文:

It is as simple as:

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

then do some error checking, hope it helps.

答案2

得分: 4

你可以使用以下代码实现:

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

playground链接

尽管我不知道Go语言在指针的有效性方面给出了什么保证,也无法想到任何使用此代码的用例。

英文:

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..

答案3

得分: 4

根据这个答案

虽然从技术上讲,你编写的代码是可行的,但有一些原因不值得信任。垃圾回收将使用你指向的内存(使用字符串)。请看以下代码的结果。

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 是 uint64 类型,如何从该值中获取指针?
}

这里是代码链接

英文:

Based on nos answer.

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(
	&quot;fmt&quot;
	&quot;strconv&quot;
	&quot;reflect&quot;
	&quot;unsafe&quot;
)

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

func main() {
	str := produce()
	
	for i := 0; i &lt; 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

huangapple
  • 本文由 发表于 2015年3月10日 23:20:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/28967512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定