Go,未获取到字符串值

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

Go, not getting string value

问题

这行代码:

fmt.Println(element.Name)

输出的是内存地址,而不是我认为应该是文件名字符串。为什么会这样?我该如何获取实际的字符串?谢谢。

另外,所有的地址都是相同的,我本来期望它们是不同的,这意味着我的 for-each 循环可能有问题。

英文:
package main

import (
	"fmt"
	"io/ioutil"
)

func main() {

	// Just count the files...
	systems,_ := ioutil.ReadDir("./XML")
	fmt.Printf("# of planetary systems\t%d\r\n", len(systems))

	// For each datafile
	for _,element := range systems {
		fmt.Println(element.Name)
	}

}

This line...

fmt.Println(element.Name)

Is outputting a memory address instead of what I assume to be the filename string. Why? How do I get the actual string? Thanks.

Also all the addresses are the same, I would expect them to difer, meaning my for-each loop might be broken.

答案1

得分: 3

FileInfo.Name(https://godoc.org/os#FileInfo)是FileInfo接口的一个函数;打印的是该函数的内存地址。要显示文件的名称,需要在打印之前对该函数进行求值:

for _, element := range systems {
    fmt.Println(element.Name())
}
英文:

FileInfo.Name is a function of the FileInfo interface; the function's memory address is being printed. To display the name of the file, you need to evaluate the function before printing:

for _, element := range systems {
    fmt.Println(element.Name())
}

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

发表评论

匿名网友

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

确定