How do I create an instance of *os.File from a string?

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

How do I create an instance of *os.File from a string?

问题

我有一个字符串,我需要将其转换为只读文件指针(*os.File)。我不能使用strings.NewReader,因为该函数只接受*os.File。这种转换是否可能?

我意识到我可以直接将字符串写入文件,然后再次打开它。但我想避免这一步骤。

英文:

I have a string that I need to be a read only file pointer (*os.File). I cannot use strings.NewReader because the function only accepts *os.File. Is this possible?

I realise I could write the string directly to a file and then open it again. But I would like to avoid this step.

答案1

得分: 4

简短回答是你不能这样做。因此,在Go语言中,通常不建议编写接受os.File的函数,除非你确实需要进行手动系统调用或其他需要os.File的操作。相反,你的函数应该接受io.Reader或另一个接口(可能包含io.Seeker),具体取决于所需的功能。

如果你可以修改需要os.File的地方,那是最好的选择。如果你不能修改,并且它实际上只需要一个读取器,你可以使用os.Pipe。

如果提供更多上下文,我可能能够给出更好的建议。

英文:

Short answer is that you can't. For this reason, it is generally not recommended in Go to write functions that take an os.File unless you are actually doing a manual syscall or something else that would require an os.File. Instead, your functions should accept an io.Reader or another interface (perhaps containing io.Seeker) depending on what is needed.

If you can modify the place that needs an os.File, that is your best bet. If you cannot and it really only needs a reader, you could use os.Pipe.

With more context, I might be able to give a better recommendation.

答案2

得分: 1

你无法直接从字符串创建*os.File。如果不能使用io.Reader,最好的方法是将字符串写入临时文件,然后使用os.Open获取*os.File

英文:

You can't create *os.File from string. If you can't use io.Reader, best bet is to write the string into temporary file and then use os.Open to get the *os.File.

huangapple
  • 本文由 发表于 2017年8月13日 08:34:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/45656090.html
匿名

发表评论

匿名网友

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

确定