StringLiteral
现在在运行时使用时会自动实现String
:
alias param = "foo" # type = StringLiteralvar runtime_value = "bar" # type = Stringvar runtime_value2 = param # type = String
alias param = "foo" # type = StringLiteralvar runtime_value = "bar" # type = Stringvar runtime_value2 = param # type = String
这样就可以实现用户期望的所有行为,而无需转换或注释类型,例如:
var string = "hello"string += " world"var if_result = "foo" if True else "bar"
var string = "hello"string += " world"var if_result = "foo" if True else "bar"
String
从 a初始化 aStringLiteral
最初指向静态常量内存,并且在第一次变异之前不执行任何分配。
编译器现在可以检测将编译时解释器堆栈内存的引用具体化为运行时代码的尝试。这包括引用内存的相关类型,例如切片、跨度和指针。
编译器目前无法跟踪内部堆栈对象在运行时具体化的生命周期,这可能会导致内存泄漏。请考虑以下示例:
fn test_comptime_materialize(): # This is ok! Forms a comptime pointer to a comptime "stack" value of # String type. alias comptime_ptr = String("foo" + "bar").unsafe_ptr() # This is ok too, dereferences the pointer at comptime, loading the byte. alias byte = comptime_ptr[] # This materializes a Byte from comptime to runtime. var rt_byte = byte # Error: cannot materialize to runtime value, the type contains an origin # referring to a compile-time value var bad_usage = comptime_ptr
fn test_comptime_materialize(): # This is ok! Forms a comptime pointer to a comptime "stack" value of # String type. alias comptime_ptr = String("foo" + "bar").unsafe_ptr() # This is ok too, dereferences the pointer at comptime, loading the byte. alias byte = comptime_ptr[] # This materializes a Byte from comptime to runtime. var rt_byte = byte # Error: cannot materialize to runtime value, the type contains an origin # referring to a compile-time value var bad_usage = comptime_ptr
以前,编译器会将值的内存表示具体化 String
,但不知道它需要被销毁。现在它会检测到这个问题。如果遇到这种情况,请重新编写代码,将完整对象(例如字符串)具体化为运行时显式:
alias comptime_string = String("foo" + "bar")var runtime_string = comptime_string
alias comptime_string = String("foo" + "bar")var runtime_string = comptime_string