Что нового
  • Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

typed and untyped variables (or constants) in Go (Golang)

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
11,696
Баллы
155
In Go (Golang), the distinction between typed and untyped variables (or constants) is important for understanding how values are treated by the compiler.

1. Typed Variables

  • A typed variable has an explicitly defined type at compile time.
  • Once a type is assigned to a variable, it cannot hold values of a different type without explicit conversion.
  • Typed variables are checked for type safety at compile time.

Example:


var x int = 42 // x is explicitly typed as `int`
var y float64 = 3.14 // y is explicitly typed as `float64`

In this case, x can only hold integer values, and y can only hold floating-point values.

2. Untyped Variables (or Constants)

  • An untyped variable (or constant) does not have a specific type assigned to it at compile time.
  • Instead, it has a default type that is inferred based on the context in which it is used.
  • Untyped values are flexible and can be used in contexts where different types are expected, as long as they are compatible.

Example:


const z = 42 // z is an untyped constant

Here, z is an untyped constant. Its type is not explicitly defined, so it can be used in various contexts where an int, float64, or other compatible types are expected.

Key Differences

AspectTyped VariablesUntyped Variables/Constants
Type DefinitionExplicitly defined (e.g., int, float64)No explicit type; inferred from context
FlexibilityRestricted to the declared typeCan be used in multiple type contexts
Type SafetyEnforced at compile timeFlexible, but may lead to implicit conversions
Examplevar x int = 42const z = 42
Example of Untyped Constants in Action


package main

import "fmt"

func main() {
const untypedConst = 42 // untyped constant

var a int = untypedConst // works: untypedConst is treated as int
var b float64 = untypedConst // works: untypedConst is treated as float64

fmt.Println(a, b) // Output: 42 42
}

In this example, untypedConst is an untyped constant. It can be assigned to both int and float64 variables without explicit conversion because its type is inferred based on the context.

Default Types for Untyped Constants


When an untyped constant is used in a context where a type is required, the compiler assigns it a default type based on its value:

  • Integer literals: int
  • Floating-point literals: float64
  • Complex literals: complex128
  • Rune literals: rune (alias for int32)
  • String literals: string

Example:


const c = 42 // default type: int
const d = 3.14 // default type: float64
const e = "hello" // default type: string


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх