Skip to content

Instantly share code, notes, and snippets.

@KevinWang15
Created June 19, 2024 03:49
Show Gist options
  • Save KevinWang15/8b7c8e94d6b76bcb14dc09b72a5c8117 to your computer and use it in GitHub Desktop.
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.
// 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