如何在Julia中将任何类型转换为String

编程入门 行业动态 更新时间:2024-10-12 05:52:31
本文介绍了如何在Julia中将任何类型转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用Julia,我想将任何类型可靠地转换为类型String.在v0.5中,似乎有两种方法可以进行转换,即string函数或String构造函数.问题是您需要根据输入类型选择合适的.

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.

例如,typeof(string(1))的计算结果为String,但是String(1)引发错误.另一方面,typeof(string(SubString{String}("a")))的计算结果为Substring{String},它不是String的子类型.相反,我们需要执行String(SubString{String}("a")).

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

因此,将任何输入x转换为类型String的唯一可靠方法似乎是通过构造:

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

String(string(x))

感觉有点麻烦.

我在这里错过了什么吗?

Am I missing something here?

推荐答案

您几乎不需要显式转换为String.请注意,即使您的类型定义具有String字段,或者您的数组具有具体的元素类型String,您仍然可以依靠隐式转换.

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中将任何类型转换为String

本文发布于:2023-11-26 20:32:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635090.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   类型   如何在   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!