F#printf字符串 [英] F# printf string
问题描述
我很困惑
let test = "aString"
let callMe =
printfn test
为什么这不起作用?在编译时抛出以下错误:
Why isn't this working? Throws below error at compile time:
类型'string'与类型'Printf.TextWriterFormat<'a>'
The type 'string' is not compatible with the type 'Printf.TextWriterFormat<'a>'
这很好:
printfn "aString"
推荐答案
这是因为format
参数实际上不是string
.它是TextWriterFormat<'T>
,F#编译器将字符串格式转换为该类型.但这不适用于string
变量,因为编译器无法在运行时将string
转换为TextWriterFormat<'T>
.
That's because the format
parameter is not actually a string
. It's TextWriterFormat<'T>
and the F# compiler converts the string format into that type. But it doesn't work on string
variables, because the compiler can't convert the string
to TextWriterFormat<'T>
at runtime.
如果您想打印变量的内容,甚至不应该尝试使用printfn
这样的方式,因为变量可能包含格式说明.
If you want to print the content of the variable, you shouldn't even try to use printfn
this way, because the variable could contain format specifications.
您可以使用%s
格式:
printfn "%s" test
或使用.Net Console.WriteLine()
:
Console.WriteLine test
如果要使用Console
类,请不要忘记在文件顶部添加open System
.
Don't forget to add open System
at the top of the file if you want to use the Console
class.
这篇关于F#printf字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!