[英]How to add a default value in record type? - F#
I was wondering if it is possible to add an initial value to the property of a type record.我想知道是否可以为类型记录的属性添加一个初始值。
type ToDo = {
Title : string
Description : string
Done : bool
}
Something like this:像这样:
Done : bool option = false
That is, I want to do something like in C #:也就是说,我想在 C # 中做类似的事情:
public class Todo
{
public string Title { get; set; }
public string Description { get; set; }
public bool Done { get; set; } = false; // Just like this
}
An alternative, (only recommended if there are valid defaults for all fields) to Fyodors solution is to use "with" in functions. Fyodors 解决方案的替代方案(仅在所有字段都有有效默认值时才推荐)是在函数中使用“with”。 Like this:像这样:
type ToDo = {
Title : string
Description : string
Done : bool
}
module ToDo =
let defaultValues =
{Title = "Give me a title"; Description = "Describe me"; Done = false}
let myToDoItem = {ToDo.defaultValues with Title = "A real title"; Description = "A real description}
No, F# does not have default values for record fields.不,F# 没有记录字段的默认值。 The usual way to go about this is to provide a "smart constructor" - ie a function that takes whatever fields are not default and constructs a record for you: go 的通常方法是提供一个“智能构造函数” - 即 function 接受任何非默认字段并为您构造一条记录:
let toDo title description =
{ Title = title; Description = description; Done = false }
let firstTodo = toDo "Buy milk" "The cat is hungry"
If you want the API to look nicer, you could also leverage anonymous records:如果您希望 API 看起来更好,您还可以利用匿名记录:
let toDo (r : {| Title: string; Description: string |}) =
{ Title = r.Title; Description = r.Description; Done = false }
let firstTodo = toDo {| Title = "Buy milk"; Description = "The cat is hungry" |}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.