Created
June 19, 2024 03:49
-
-
Save KevinWang15/8b7c8e94d6b76bcb14dc09b72a5c8117 to your computer and use it in GitHub Desktop.
MustConvertType converts an instance of type A to type B using JSON marshal and unmarshal.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MustConvertType converts an instance of type A to type B using JSON marshal and unmarshal. | |
// Both types A and B should have the same structure and JSON tags. | |
// In case of error, it panics. | |
func MustConvertType[A any, B any](input A) B { | |
var output B | |
// Marshal the input type A to JSON | |
data, err := json.Marshal(input) | |
if err != nil { | |
panic(fmt.Errorf("failed to marshal input: %w", err)) | |
} | |
// Unmarshal the JSON data to type B | |
err = json.Unmarshal(data, &output) | |
if err != nil { | |
panic(fmt.Errorf("failed to unmarshal to output: %w", err)) | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment