常见的 Go 变量缩写对照表

Go 语言推荐使用简写来命名变量,以下是常见的对照表:

缩写 对应名称
var a int // array
var arg []string // arg­ument
var b []byte // buffer
var b byte // byte
var bs bytes // by­tes
var buf []byte // buffer
var c int // ca­pacity
var c int // ch­aracter
var dst int // ds­t­ination
var err error // error value
var fv string // flag value
var i int // index
var l int // length
var m int // another number
var msg string // ms­age
var n int // number or number of
var num int // number
var off int // offset
var op int // op­eration
var parsed bool // parsed ok?
var pkg string // pa­c­k­age
var pos int // pos­ition
var r rune // rune
var r io.Reader // reader
var s string // string
var seen bool // has seen?
var sep string // sep­arator
var src int // so­u­rce
var str string // string
var v string // value
var val string // value
var w io.Writer // writer

除此之外,github.com/BluntSporks/abbreviatio... 这个项目的 Readme 也提供一些例子供参考:

  • abbrev = abbreviate, abbreviation
  • abs = absolute
  • acc = accuracy, accurate, account
  • accum = accumulate, accumulation, accumulator
  • act = actual
  • addr = address
  • aggr = aggregate, aggregation
  • alg = algebra
  • algo = algorithm
  • alloc = allocate, allocation
  • amp = ampersand
  • anc = ancestor
  • ans = answer
  • apos = apostrophe
  • approx = approximate, approximation
  • arch = architect, architecture
  • arg = argument
  • asc = ascending
  • assoc = associative, associate
  • attr = attribute
  • auth = authenticate, authentication, authorize, authorization
  • avg = average
  • bin = binary, binomial
  • biz = business
  • bool = boolean
  • buf = buffer
  • cal = calendar
  • calc = calculate, calculation, calculator, calculus
  • cap = capitalize, capitalization, capacity
  • ceil = ceiling
  • cert = certify, certificate, certification
  • chan = channel
  • char = character
  • coef = coefficient
  • col = column
  • coll = collect, collection
  • comb = combine, combination
  • comp = compare, comparison, compensate, compensation
  • cond = condition
  • config = configure, configuration
  • conn = connect, connection, connector
  • cont = continue, continuation, contain, container
  • conv = convert, conversion
  • cop = complex
  • corr = correlate, correlation
  • covar = covariance
  • crypt = cryptography, cryptology, cryptanalysis, cryptosystem
  • cur = current
  • cust = customer
  • dec = decimal, decrement, decode, decrypt
  • decl = declare, declaration
  • def = define, definition
  • deg = degree
  • del = delete, deletion
  • delim = delimiter
  • den = denomination, denominator
  • dep = depend, dependent
  • dept = department
  • desc = descendant, descending, describe, description
  • deser = deserialize, deserialization
  • dest = destination
  • det = determinant
  • dev = deviate, deviation, develop, development
  • diag = diagonal, diagnosis, diagnostic
  • diam = diameter
  • dic = dictionary
  • diff = difference
  • dig = digest
  • dim = dimension
  • dir = directory, directive, direct, direction
  • disc = discriminant
  • dist = distribute, distribution, distributor, distance
  • div = divide
  • doc = document, documentation
  • dom = domain
  • dupe = duplicate, duplication
  • elem = element
  • empl = employee, employment
  • enc = encode, encrypt
  • enum = enumeration
  • env = environment
  • equiv = equivalent, equivalence
  • err = error
  • esc = escape
  • est = estimate, estimation
  • eval = evaluate, evaluation
  • excl = exclude, exclusion, exclamation
  • excp = except, exception
  • exec = execute, execution
  • exp = exponent, expect
  • expr = express, expression
  • ext = extend, extension, external
  • fact = factorial
  • fem = feminine
  • fig = figure
  • float = floating
  • frac = fraction
  • freq = frequent, frequency
  • func = function
  • gen = generate, generation, generator, general, generic
  • geo = geography, geographic
  • geom = geometric
  • guar = guarantee
  • har = harmonic
  • hex = hexadecimal
  • horiz = horizontal
  • ident = identification, identifier
  • imag = imaginary
  • imm = immediate
  • impl = implement, implementation
  • inc = increment
  • incl = include, inclusion
  • ind = indirect, indicate, indication
  • indep = independent
  • inf = infinite, infinity
  • info = information
  • init = initial, initialize, initialization
  • ins = insert, insertion
  • inst = instance, instantiate, instruction
  • int = integer, internal
  • intc = intercept
  • intf = interface
  • inv = inverse
  • iter = iterate, iteration, iterator
  • kurt = kurtosis
  • lang = language
  • len = length
  • lex = lexicon
  • lib = library
  • lim = limit, limitation
  • lin = linear
  • lit = literal
  • loc = locate, location, locale
  • log = logarithm
  • low = lowercase
  • mant = mantissa
  • masc = masculine
  • max = maximum
  • med = medium, median
  • mem = memory
  • min = minimum, minute
  • mod = modulo, modify, modification, module
  • mul = multiply
  • multi = multiple
  • mut = mutate, mutation, mutable
  • mutex = mutual exclusion
  • nat = natural
  • neg = negate, negation, negative
  • net = network
  • num = number, numeration, numerator
  • obj = object
  • oct = octal
  • op = operate, operation, operator
  • opt = option
  • orig = original, originate, origination
  • ovfl = overflow
  • pal = palette
  • par = parent
  • para = paragraph
  • param = parameter
  • pat = pattern
  • perf = perform, performance
  • perim = perimeter
  • perm = permutation, permanent
  • perp = perpendicular
  • phon = phonetic
  • pic = picture
  • pos = positive, position
  • poss = possible, possibly
  • prec = precise, precision
  • pref = prefer, preference
  • prep = prepare, preparation
  • prev = previous
  • pri = private, primary
  • prio = priority, prioritize
  • prob = probability
  • proc = procedure, process
  • prod = product
  • prof = profile
  • prog = program, progress
  • proj = project
  • pron = pronounce, pronunciation
  • prop = proportion
  • prot = protocol
  • proto = prototype
  • pub = public
  • punc = punctuate, punctuation
  • quad = quadratic
  • ques = question
  • quot = quotient
  • rad = radian, radius, radical
  • rand = random
  • rec = recursive, record
  • rect = rectangle
  • recv = receive
  • ref = reference
  • reg = register, regular
  • regexp = regular expression
  • rel = relate, relation, relative
  • rem = remainder, remove
  • ren = rename
  • rep = repeat, repetition
  • repl = replace, replacement
  • repo = repository
  • repr = represent, representation, representative
  • req = require, requirement
  • res = resource, result, resolve, resolution
  • resp = respond, response, responsive
  • ret = return
  • rev = reverse
  • san = sanitize, sanitization
  • sched = schedule
  • sci = science, scientific
  • sec = second, secondary, secure, security, section
  • seg = segment
  • sel = select, selection
  • sem = semaphore
  • sent = sentence
  • sep = separate, separation, separator
  • seq = sequence
  • ser = serial, serialize, serialization, series
  • sig = signal, signature
  • sim = simulate, simulation
  • sing = singular
  • sock = socket
  • spec = specify, specification, specific
  • stat = statistic
  • sub = subtract
  • syll = syllable
  • symm = symmetry
  • sync = synchronized
  • sys = system
  • tan = tangent
  • tech = technology
  • temp = temporary
  • term = terminate, termination, terminal
  • thru = through
  • tok = token, tokenize
  • trig = trigonometry
  • up = uppercase
  • upd = update
  • util = utility
  • val = value, validate, validation
  • var = variance, variable
  • vec = vector
  • ver = version, verify, verification
  • vert = vertical
  • vis = visible, visibility
  • vol = volume
  • win = window
  • xfer = transfer
  • xlat = translate, translation
  • xmit = transmit
  • xor = exclusive or
  • xpar = transparent, transparency
  • xpos = transpose, transposition

Not in combination

These are OK to use as whole words, or at the beginning or end of a camelcased word, but try not to use them in the middle of words due to their lack of vowels.

  • cmd = command
  • cmp = compare, comparison
  • cnt = count
  • ctl = control
  • ctx = context
  • cvt = convert
  • dst = destination
  • fld = field
  • fmt = format
  • fwd = forward
  • hdl = handle
  • hdr = header
  • i18n = internationalization
  • l10n = localization
  • msg = message
  • pkg = package
  • ptr = pointer
  • qry = query
  • src = source
  • srv = server
  • std = standard
  • stm = statement
  • str = string
  • tbl = table
本作品采用《CC 协议》,转载必须注明作者和本文链接
摈弃世俗浮躁,追求技术精湛
本帖由系统于 2年前 自动加精
Summer
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!