OCaml类型不匹配错误:string t与string类型问题求助
OCaml异步API调用错误修复
问题原因
错误提示里的string t指的是string Lwt.t——Lwt异步库的异步值类型。Cohttp_lwt.Body.to_string返回的不是直接的字符串,而是一个异步计算任务,必须通过Lwt的绑定操作提取实际字符串后才能使用。
修正后的代码
open Lwt open Cohttp open Cohttp_lwt_unix let call_api config ip add_on lang = let protocol = if config.use_ssl then "https" else "http" in let uri = Uri.of_string (protocol ^ "://api.example.com/v2/?key=" ^ config.api_key ^ "&ip=" ^ ip ^ "&package=" ^ config.api_package ^ "&addon=" ^ add_on ^ "&lang=" ^ lang) in Lwt_main.run begin Client.get uri >>= fun (resp, body) -> let code = resp |> Response.status |> Code.code_of_status in -- 用>>=绑定异步操作,提取实际的字符串值 body |> Cohttp_lwt.Body.to_string >>= fun json -> printf "JSON: %s\n" json; -- 用Lwt.return包装要返回的元组,符合异步流程的返回要求 Lwt.return (code, json) end
关键修正点
- 替换原代码中直接赋值
json的逻辑,用>>=绑定Cohttp_lwt.Body.to_string的结果,获取实际的字符串。 - 异步流程的最终返回值必须用
Lwt.return包装,确保类型匹配('a * 'b) Lwt.t,这样Lwt_main.run才能正确执行并返回同步的int * string元组。
内容的提问来源于stack exchange,提问作者Vlam
相关产品推荐
相关产品推荐

