如何在 Julia 中将任何类型转换为字符串 [英] How to convert any type into String in Julia

查看:13
本文介绍了如何在 Julia 中将任何类型转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Using Julia, I'd like to reliably convert any type into type String. There seems to be two ways to do the conversion in v0.5, either the string function or String constructor. The problem is that you need to choose the right one depending upon the input type.

For example, typeof(string(1)) evaluates to String, but String(1) throws an error. On the other hand, typeof(string(SubString{String}("a"))) evaluates to Substring{String}, which is not a subtype of String. We instead need to do String(SubString{String}("a")).

So it seems the only reliable way to convert any input x to type String is via the construct:

String(string(x))

which feels a bit cumbersome.

Am I missing something here?

解决方案

You should rarely need to explicitly convert to String. Note that even if your type definitions have String fields, or if your arrays have concrete element type String, you can still rely on implicit conversion.

For instance, here are examples of implicit conversion:

type TestType
    field::String
end

obj = TestType(split("x y")[1])  # construct TestType with a SubString
obj.field  # the String "x"

obj.field = SubString("Hello", 1, 3)  # assign a SubString
obj.field  # the String "Hel"

这篇关于如何在 Julia 中将任何类型转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆