F# type constraint for record type with specific property

前端 未结 3 1423
失恋的感觉
失恋的感觉 2021-01-17 22:01

I\'m trying to create a generic function which requires of its type argument that it is a record type, and that it has a specific property. Here\'s a sample that generates t

3条回答
  •  别那么骄傲
    2021-01-17 22:50

    I would suggest reading Tomas' answer first. Using statically resolved type constraints should generally be avoided when possible. They're a feature of the F# compiler rather than .NET so they do, to some extent, restrict the reusability of your code. That said, they are very powerful and do allow you to impose useful constraints at compile time.

    The syntax for using them is also not terribly pleasant but if you remain undeterred, you could do something like this:

    type Test = {Bar : string}
    
    let inline foo (a : ^a) =
        "foo " + ((^a) : (member Bar : string) (a))
    
    let foobar = foo {Bar = "bar"} // prints "foo bar"
    

    Note however that you can't actually restrict the type to being a record, simply something that has a member Bar of type string. So this would also resolve:

    type Test2(str : string) = member this.Bar = str
    
    let foobar2 = foo (Test2("bar")) // prints "foo bar"
    

提交回复
热议问题