Skip to content

Commit f65fd5b

Browse files
committed
Go: implement type casting
Resolves kaitai-io/kaitai_struct#931
1 parent 1d64d11 commit f65fd5b

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

shared/src/main/scala/io/kaitai/struct/translators/GoTranslator.scala

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,22 @@ class GoTranslator(out: StringLanguageOutputWriter, provider: TypeProvider, impo
291291
}
292292
}
293293

294-
override def doCast(value: Ast.expr, typeName: DataType): TranslatorResult = ???
294+
override def doCast(value: Ast.expr, typeName: DataType): TranslatorResult = {
295+
val valueType = detectType(value)
296+
valueType match {
297+
case KaitaiStructType | CalcKaitaiStructType(_) | AnyType =>
298+
// Type assertion - only works on interfaces, otherwise a syntax error would occur
299+
ResultString(s"${translate(value, METHOD_PRECEDENCE)}.(${GoCompiler.kaitaiType2NativeType(typeName)})")
300+
// These data types are represented as pointer types (`*T`) in the generated Go
301+
// code, so they have to be wrapped into parentheses, otherwise Go will attempt to
302+
// apply `*` to the result of `T(...)` instead of the desired `(*T)(...)`.
303+
case KaitaiStreamType | OwnedKaitaiStreamType | _: UserType =>
304+
ResultString(s"(${GoCompiler.kaitaiType2NativeType(typeName)})(${translate(value)})")
305+
case _ =>
306+
// Type conversion - for everything else that is not an interface
307+
ResultString(s"${GoCompiler.kaitaiType2NativeType(typeName)}(${translate(value)})")
308+
}
309+
}
295310

296311
override def doArrayLiteral(t: DataType, value: Seq[Ast.expr]) =
297312
ResultString(s"[]${GoCompiler.kaitaiType2NativeType(t)}{${value.map(translate).mkString(", ")}}")

0 commit comments

Comments
 (0)