简体   繁体   中英

How to define a record field as an array in f#?

I want to create a record field of type byte array with 8 elements but couldn't figure out the correct syntax.

I did something like:

let dataRecord = {
    id : int
    data : byte array 
}

let dataValues : byte array = Array.zeroCreate 8

let myArray = { id = 0; data = dataValues }

Can it be done in the record definition? How?

My example, above, seemed to work but I don't know if it is safe or the best or most correct way.

There's nothing wrong with what you're currently doing (other than that your type definition is using let instead of type ), so it's not completely clear to me what you're asking for. Maybe something like this?

type dataRecord = {
    id : int
    data : byte array
}

let myRecord = { id = 0; data = [| for i in 1 .. 8 -> 0uy |] }

You could also just use { id = 0; data = Array.zeroCreate 8 } { id = 0; data = Array.zeroCreate 8 } if you'd like - array literals are often a bit easier to read, but zeroCreate is probably more efficient if you're creating big arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM