F# printf 字符串 [英] F# printf string

查看:22
本文介绍了F# printf 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑

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屋!

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