How would you do decode this json in a type safe way using Go?
{"purchaseType": "Rent","price": 0.99,"title": "inception"}
Here is an implementation in Haskell: {-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import GHC.Generics
import qualified Data.ByteString.Lazy as BL
data PurchaseType = Free | Rent | Buy | Subscriber deriving (Show, Generic)
instance FromJSON PurchaseType
instance ToJSON PurchaseType
data Media = Media { title :: String, price :: Float, purchaseType :: PurchaseType} deriving (Show, Generic)
instance FromJSON Media
instance ToJSON Media
jsonData = "{\"title\": \"inception\", \"price\": 0.99, \"purchaseType\": \"Rent\"}"
main = print $ (decode jsonData :: Maybe Media)
-- running main gets:
-- λ> main
-- Just (Media {title = "inception", price = 0.99, purchaseType = Rent})
EDIT: Spec Change, boss wants an order confirmation message! orderConfirmationMessage (Media mediaTitle _ Rent) = putStrLn ("Thanks for renting " ++ mediaTitle)
Then we recompile and... what's this? Main.hs:19:1-100: Warning: …
Pattern match(es) are non-exhaustive
In an equation for ‘orderConfirmationMessage’:
Patterns not matched:
Media _ _ Free
Media _ _ Buy
Media _ _ Subscriber
Good thing GHC had told us Free/Buy/Subscriber's needed messages instead of our boss! In fact, had I been using -Wall this would be a compile time error.Getting to the point, my real questions are:
1. What is Go's way of ensuring your function handles cases like this, or is there an idiomatic way of avoiding it?
2. How do you discern between MovieType's without resorting to just using Strings and compromising type safety?