棄用 API

最後更新


依「從哪個版本開始棄用」列出標準庫中所有標記為 Deprecated 的 API;棄用的 API 仍可編譯,但官方建議改用說明中的替代做法,本書範例一律不使用。
棄用版本的判定方式:比對每個 Go 主版本的原始碼,找出該 API 的文件註解第一次出現 Deprecated: 的版本。

go1.27


Go 版本頁
套件符號官方說明
crypto/tlsConfig.Randthis should be left nil in production. Not all TLS configurations are guaranteed to use Rand. Test code can use [testing/cryptotest.SetGlobalRandom] instead.

go1.26


Go 版本頁
套件符號官方說明
crypto/ecdsaPrivateKey.Dmodifying the raw value can produce invalid keys, and may invalidate internal optimizations; moreover, [big.Int] methods are not suitable for operating on cryptographic values. To encode and decode PrivateKey values, use [PrivateKey.Bytes] and [ParseRawPrivateKey] or [crypto/x509.MarshalPKCS8PrivateKey] and [crypto/x509.ParsePKCS8PrivateKey]. For ECDH, use [crypto/ecdh].
crypto/ecdsaPublicKey.Xmodifying the raw coordinates can produce invalid keys, and may invalidate internal optimizations; moreover, [big.Int] methods are not suitable for operating on cryptographic values. To encode and decode PublicKey values, use [PublicKey.Bytes] and [ParseUncompressedPublicKey] or [crypto/x509.MarshalPKIXPublicKey] and [crypto/x509.ParsePKIXPublicKey]. For ECDH, use [crypto/ecdh]. For lower-level elliptic curve operations, use a third-party module like filippo.io/nistec.
crypto/ecdsaPublicKey.Ymodifying the raw coordinates can produce invalid keys, and may invalidate internal optimizations; moreover, [big.Int] methods are not suitable for operating on cryptographic values. To encode and decode PublicKey values, use [PublicKey.Bytes] and [ParseUncompressedPublicKey] or [crypto/x509.MarshalPKIXPublicKey] and [crypto/x509.ParsePKIXPublicKey]. For ECDH, use [crypto/ecdh]. For lower-level elliptic curve operations, use a third-party module like filippo.io/nistec.
crypto/rsaDecryptPKCS1v15PKCS #1 v1.5 encryption is dangerous and should not be used. Whether this function returns an error or not discloses secret information. If an attacker can cause this function to run repeatedly and learn whether each instance returned an error then they can decrypt and forge signatures as if they had the private key. See [draft-irtf-cfrg-rsa-guidance-05] for more information. Use [EncryptOAEP] and [DecryptOAEP] instead.
crypto/rsaDecryptPKCS1v15SessionKeyPKCS #1 v1.5 encryption is dangerous and should not be used. The protections implemented by this function are limited and fragile, as explained above. See [draft-irtf-cfrg-rsa-guidance-05] for more information. Use [EncryptOAEP] and [DecryptOAEP] instead.
crypto/rsaEncryptPKCS1v15PKCS #1 v1.5 encryption is dangerous and should not be used. See [draft-irtf-cfrg-rsa-guidance-05] for more information. Use [EncryptOAEP] and [DecryptOAEP] instead.
crypto/rsaPKCS1v15DecryptOptionsPKCS #1 v1.5 encryption is dangerous and should not be used. See [draft-irtf-cfrg-rsa-guidance-05] for more information. Use [EncryptOAEP] and [DecryptOAEP] instead.
net/http/httputilReverseProxy.DirectorUse Rewrite instead.

go1.25


Go 版本頁
套件符號官方說明
go/astFilterFuncDuplicatesuse the type checker [go/types] instead of [Package]; see [Object].
go/astFilterImportDuplicatesuse the type checker [go/types] instead of [Package]; see [Object].
go/astFilterPackageuse the type checker [go/types] instead of [Package]; see [Object]. Alternatively, use [FilterFile].
go/astFilterUnassociatedCommentsuse the type checker [go/types] instead of [Package]; see [Object].
go/astMergeModeuse the type checker [go/types] instead of [Package]; see [Object].
go/astMergePackageFilesthis function is poorly specified and has unfixable bugs; also [Package] is deprecated.
go/astPackageExportsuse the type checker [go/types] instead of [Package]; see [Object]. Alternatively, use [FileExports].
go/parserParseDirParseDir does not consider build tags when associating files with packages. For precise information about the relationship between packages and files, use golang.org/x/tools/go/packages, which can also optionally parse and type-check the files too.

go1.24


Go 版本頁
套件符號官方說明
crypto/cipherNewCFBDecrypterCFB mode is not authenticated, which generally enables active attacks to manipulate and recover the plaintext. It is recommended that applications use [AEAD] modes instead. The standard library implementation of CFB is also unoptimized and not validated as part of the FIPS 140-3 module. If an unauthenticated [Stream] mode is required, use [NewCTR] instead.
crypto/cipherNewCFBEncrypterCFB mode is not authenticated, which generally enables active attacks to manipulate and recover the plaintext. It is recommended that applications use [AEAD] modes instead. The standard library implementation of CFB is also unoptimized and not validated as part of the FIPS 140-3 module. If an unauthenticated [Stream] mode is required, use [NewCTR] instead.
crypto/cipherNewOFBOFB mode is not authenticated, which generally enables active attacks to manipulate and recover the plaintext. It is recommended that applications use [AEAD] modes instead. The standard library implementation of OFB is also unoptimized and not validated as part of the FIPS 140-3 module. If an unauthenticated [Stream] mode is required, use [NewCTR] instead.
runtimeGOROOTThe root used during the Go build will not be meaningful if the binary is copied to another machine. Use the system path to locate the “go” binary, and use “go env GOROOT” to find its GOROOT.

go1.22


Go 版本頁
套件符號官方說明
go/astImporteruse the type checker [go/types] instead; see [Object].
go/astNewPackageuse the type checker [go/types] instead; see [Object].
go/astObjectThe relationship between Idents and Objects cannot be correctly computed without type information. For example, the expression T{K: 0} may denote a struct, map, slice, or array literal, depending on the type of T. If T is a struct, then K refers to a field of T, whereas for the other types it refers to a value in the environment.
go/astPackageuse the type checker [go/types] instead; see [Object].
go/astScopeuse the type checker [go/types] instead; see [Object].
html/templateErrJSTemplateErrJSTemplate is no longer returned when an action is present in a JS template literal. Actions inside of JS template literals are now escaped as expected.
reflectPtrToSuperseded by [PointerTo].

go1.21


Go 版本頁
套件符號官方說明
crypto/ellipticCurve.Addthis is a low-level unsafe API.
crypto/ellipticCurve.Doublethis is a low-level unsafe API.
crypto/ellipticCurve.IsOnCurvethis is a low-level unsafe API. For ECDH, use the crypto/ecdh package. The NewPublicKey methods of NIST curves in crypto/ecdh accept the same encoding as the Unmarshal function, and perform on-curve checks.
crypto/ellipticCurve.ScalarBaseMultthis is a low-level unsafe API. For ECDH, use the crypto/ecdh package. Most uses of ScalarBaseMult can be replaced by a call to the PrivateKey.PublicKey method in crypto/ecdh.
crypto/ellipticCurve.ScalarMultthis is a low-level unsafe API. For ECDH, use the crypto/ecdh package. Most uses of ScalarMult can be replaced by a call to the ECDH methods of NIST curves in crypto/ecdh.
crypto/ellipticCurveParams.Addthe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.Doublethe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.IsOnCurvethe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.ScalarBaseMultthe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticCurveParams.ScalarMultthe [CurveParams] methods are deprecated and are not guaranteed to provide any security property. For ECDH, use the [crypto/ecdh] package. For ECDSA, use the [crypto/ecdsa] package with a [Curve] value returned directly from [P224], [P256], [P384], or [P521].
crypto/ellipticGenerateKeyfor ECDH, use the GenerateKey methods of the [crypto/ecdh] package; for ECDSA, use the GenerateKey function of the crypto/ecdsa package.
crypto/ellipticMarshalfor ECDH, use the crypto/ecdh package. This function returns an encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.
crypto/ellipticUnmarshalfor ECDH, use the crypto/ecdh package. This function accepts an encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.
crypto/rsaGenerateMultiPrimeKeyThe use of this function with a number of primes different from two is not recommended for the above security, compatibility, and performance reasons. Use [GenerateKey] instead.
crypto/rsaPrecomputedValues.CRTValuesThese values are still filled in by Precompute for backwards compatibility but are not used. Multi-prime RSA is very rare, and is implemented by this package without CRT optimizations to limit complexity.
crypto/x509RevocationList.RevokedCertificatesUse RevokedCertificateEntries instead.
reflectSliceHeaderUse unsafe.Slice or unsafe.SliceData instead.
reflectStringHeaderUse unsafe.String or unsafe.StringData instead.

go1.20


Go 版本頁
套件符號官方說明
math/randReadFor almost all use cases, [crypto/rand.Read] is more appropriate. If a deterministic source is required, use [math/rand/v2.ChaCha8.Read].
math/randSeedAs of Go 1.20 there is no reason to call Seed with a random value. Programs that call Seed with a known value to get a specific sequence of results should use New(NewSource(seed)) to obtain a local random generator.

go1.19


Go 版本頁
套件符號官方說明
crypto/x509Certificate.CheckCRLSignatureUse [RevocationList.CheckSignatureFrom] instead.
crypto/x509Certificate.CreateCRLthis method does not generate an RFC 5280 conformant X.509 v2 CRL. To generate a standards compliant CRL, use [CreateRevocationList] instead.
crypto/x509ParseCRLUse [ParseRevocationList] instead.
crypto/x509ParseDERCRLUse [ParseRevocationList] instead.
crypto/x509/pkixCertificateListx509.RevocationList should be used instead.
crypto/x509/pkixTBSCertificateListx509.RevocationList should be used instead.
go/docSynopsisNew programs should use [Package.Synopsis] instead, which handles links in text properly.
go/docToHTMLToHTML cannot identify documentation links in the doc comment, because they depend on knowing what package the text came from, which is not included in this API.
go/docToTextToText cannot identify documentation links in the doc comment, because they depend on knowing what package the text came from, which is not included in this API.
io/ioutil(package)As of Go 1.16, the same functionality is now provided by package [io] or package [os], and those implementations should be preferred in new code. See the specific function documentation for details.
io/ioutilDiscardAs of Go 1.16, this value is simply [io.Discard].
io/ioutilNopCloserAs of Go 1.16, this function simply calls [io.NopCloser].
io/ioutilReadAllAs of Go 1.16, this function simply calls [io.ReadAll].
io/ioutilReadDirAs of Go 1.16, [os.ReadDir] is a more efficient and correct choice: it returns a list of [fs.DirEntry] instead of [fs.FileInfo], and it returns partial results in the case of an error midway through reading a directory.
io/ioutilReadFileAs of Go 1.16, this function simply calls [os.ReadFile].
io/ioutilTempDirAs of Go 1.17, this function simply calls [os.MkdirTemp].
io/ioutilTempFileAs of Go 1.17, this function simply calls [os.CreateTemp].
io/ioutilWriteFileAs of Go 1.16, this function simply calls [os.WriteFile].

go1.18


Go 版本頁
套件符號官方說明
bytesTitleThe rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.
crypto/tlsConfig.PreferServerCipherSuitesPreferServerCipherSuites is ignored.
crypto/x509CertPool.Subjectsif s was returned by [SystemCertPool], Subjects will not include the system roots.
go/typesInterface.EmbeddedUse [Interface.EmbeddedType] which is not restricted to defined (*[Named]) types.
go/typesNewInterfaceUse NewInterfaceType instead which allows arbitrary embedded types.
go/typesNewSignatureUse [NewSignatureType] instead which allows for type parameters.
netError.TemporaryTemporary errors are not well-defined. Most "temporary" errors are timeouts, and the few exceptions are surprising. Do not use this method.
stringsTitleThe rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.
syscallSyscallUse [SyscallN] instead.
syscallSyscall12Use [SyscallN] instead.
syscallSyscall15Use [SyscallN] instead.
syscallSyscall18Use [SyscallN] instead.
syscallSyscall6Use [SyscallN] instead.
syscallSyscall9Use [SyscallN] instead.

go1.17


Go 版本頁
套件符號官方說明
reflectValue.InterfaceDataThe memory representation of interface values is not compatible with InterfaceData.
syscallCreateIoCompletionPortCreateIoCompletionPort has the wrong function signature. Use x/sys/windows.CreateIoCompletionPort.
syscallGetQueuedCompletionStatusGetQueuedCompletionStatus has the wrong function signature. Use x/sys/windows.GetQueuedCompletionStatus.
syscallPostQueuedCompletionStatusPostQueuedCompletionStatus has the wrong function signature. Use x/sys/windows.PostQueuedCompletionStatus.

go1.16


Go 版本頁
套件符號官方說明
crypto/dsa(package)DSA is a legacy algorithm, and modern alternatives such as Ed25519 (implemented by package crypto/ed25519) should be used instead. Keys with 1024-bit moduli (L1024N160 parameters) are cryptographically weak, while bigger keys are not widely supported. Note that FIPS 186-5 no longer approves DSA for signature generation.
crypto/x509DecryptPEMBlockLegacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.
crypto/x509EncryptPEMBlockLegacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.
crypto/x509IsEncryptedPEMBlockLegacy PEM encryption as specified in RFC 1423 is insecure by design. Since it does not authenticate the ciphertext, it is vulnerable to padding oracle attacks that can let an attacker recover the plaintext.

go1.15


Go 版本頁
套件符號官方說明
crypto/tlsConfig.SessionTicketKeyif this field is left at zero, session ticket keys will be automatically rotated every day and dropped after seven days. For customizing the rotation schedule or synchronizing servers that are terminating connections for the same host, use SetSessionTicketKeys.
crypto/tlsConnectionState.NegotiatedProtocolIsMutualthis value is always true.

go1.14


Go 版本頁
套件符號官方說明
crypto/tlsConfig.BuildNameToCertificateNameToCertificate only allows associating a single certificate with a given name. Leave that field nil to let the library select the first compatible chain from Certificates.
crypto/tlsConfig.NameToCertificateNameToCertificate only allows associating a single certificate with a given name. Leave this field nil to let the library select the first compatible chain from Certificates.
net/httpTransport.DialTLSUse DialTLSContext instead, which allows the transport to cancel dials as soon as they are no longer needed. If both are set, DialTLSContext takes priority.

go1.13


Go 版本頁
套件符號官方說明
crypto/tlsVersionSSL30SSLv3 is cryptographically broken, and is no longer supported by this package. See golang.org/issue/32716.
debug/gosymLineTable.LineToPCUse Table's LineToPC method instead.
debug/gosymLineTable.PCToLineUse Table's PCToLine method instead.
imageZPUse a literal [image.Point] instead.
imageZRUse a literal [image.Rectangle] instead.

go1.12


Go 版本頁
套件符號官方說明
crypto/rc4Cipher.ResetReset can't guarantee that the key will be entirely removed from the process's memory.
crypto/x509CertificateRequest.AttributesUse Extensions and ExtraExtensions instead for parsing and generating the requestedExtensions attribute.
go/importerForUse [ForCompiler], which populates a FileSet with the positions of objects created by the importer.
netDialer.DualStackFast Fallback is enabled by default. To disable, set FallbackDelay to a negative value.
net/httpErrUnexpectedTrailerErrUnexpectedTrailer is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.
regexpRegexp.CopyIn earlier releases, when using a [Regexp] in multiple goroutines, giving each goroutine its own copy helped to avoid lock contention. As of Go 1.12, using Copy is no longer necessary to avoid lock contention. Copy may still be appropriate if the reason for its use is to make two copies with different [Regexp.Longest] settings.

go1.11


Go 版本頁
套件符號官方說明
archive/tarTypeRegAUse TypeReg instead.
net/httpCloseNotifierthe CloseNotifier interface predates Go's context package. New code should use [Request.Context] instead.
net/http/httptestResponseRecorder.HeaderMapHeaderMap exists for historical compatibility and should not be used. To access the headers returned by a handler, use the Response.Header map as returned by the Result method.

go1.10


Go 版本頁
套件符號官方說明
archive/tarHeader.XattrsUse PAXRecords instead.
archive/zipFileHeader.ModTimeUse [Modified] instead.
archive/zipFileHeader.ModifiedDateUse Modified instead.
archive/zipFileHeader.ModifiedTimeUse Modified instead.
archive/zipFileHeader.SetModTimeUse [Modified] instead.
encoding/csvErrTrailingCommaErrTrailingComma is no longer used.
encoding/csvReader.TrailingCommaTrailingComma is no longer used.

go1.9


Go 版本頁
套件符號官方說明
database/sql/driverColumnConverterDrivers should implement [NamedValueChecker].
runtimeCPUProfileUse the [runtime/pprof] package, or the handlers in the [net/http/pprof] package, or the [testing] package's -test.cpuprofile flag instead.

go1.8


Go 版本頁
套件符號官方說明
database/sql/driverConn.BeginDrivers should implement ConnBeginTx instead (or additionally).
database/sql/driverExecerDrivers should implement [ExecerContext] instead.
database/sql/driverQueryerDrivers should implement [QueryerContext] instead.
database/sql/driverStmt.ExecDrivers should implement StmtExecContext instead (or additionally).
database/sql/driverStmt.QueryDrivers should implement StmtQueryContext instead (or additionally).
net/httpErrHeaderTooLongErrHeaderTooLong is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.
net/httpErrMissingContentLengthErrMissingContentLength is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.
net/httpErrShortBodyErrShortBody is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.
net/httpProtocolErrorNot all errors in the http package related to protocol errors are of type ProtocolError.
net/http/httputilErrClosedNo longer used.
net/http/httputilErrPersistEOFNo longer used.
net/http/httputilErrPipelineNo longer used.
path/filepathHasPrefixHasPrefix does not respect path boundaries and does not ignore case when required.

go1.7


Go 版本頁
套件符號官方說明
go/buildAllowBinaryThe supported way to create a compiled-only package is to write source code containing a //go:binary-only-package comment at the top of the file. Such a package will be recognized regardless of this flag setting (because it has source code) and will have BinaryOnly set to true in the returned Package.
netDialer.CancelUse DialContext instead.
net/httpErrWriteAfterFlushErrWriteAfterFlush is no longer returned by anything in the net/http package. Callers should not compare errors against this variable.
net/httpRequest.CancelSet the Request's context with NewRequestWithContext instead. If a Request's Cancel field and context are both set, it is undefined whether Cancel is respected.
net/httpTransport.DialUse DialContext instead, which allows the transport to cancel dials as soon as they are no longer needed. If both are set, DialContext takes priority.
net/http/httputilClientConnUse Client or Transport in package [net/http] instead.
net/http/httputilNewClientConnUse the Client or Transport in package [net/http] instead.
net/http/httputilNewProxyClientConnUse the Client or Transport in package [net/http] instead.
net/http/httputilNewServerConnUse the Server in package [net/http] instead.
net/http/httputilServerConnUse the Server in package [net/http] instead.
osSEEK_CURUse io.SeekStart, io.SeekCurrent, and io.SeekEnd.
osSEEK_ENDUse io.SeekStart, io.SeekCurrent, and io.SeekEnd.
osSEEK_SETUse io.SeekStart, io.SeekCurrent, and io.SeekEnd.
syscallAttachLsfUse golang.org/x/net/bpf instead.
syscallBpfBuflenUse golang.org/x/net/bpf instead.
syscallBpfDatalinkUse golang.org/x/net/bpf instead.
syscallBpfHeadercmplUse golang.org/x/net/bpf instead.
syscallBpfInterfaceUse golang.org/x/net/bpf instead.
syscallBpfJumpUse golang.org/x/net/bpf instead.
syscallBpfStatsUse golang.org/x/net/bpf instead.
syscallBpfStmtUse golang.org/x/net/bpf instead.
syscallBpfTimeoutUse golang.org/x/net/bpf instead.
syscallCheckBpfVersionUse golang.org/x/net/bpf instead.
syscallDetachLsfUse golang.org/x/net/bpf instead.
syscallFlushBpfUse golang.org/x/net/bpf instead.
syscallInterfaceAddrMessageUse golang.org/x/net/route instead.
syscallInterfaceAnnounceMessageUse golang.org/x/net/route instead.
syscallInterfaceMessageUse golang.org/x/net/route instead.
syscallInterfaceMulticastAddrMessageUse golang.org/x/net/route instead.
syscallLsfJumpUse golang.org/x/net/bpf instead.
syscallLsfSocketUse golang.org/x/net/bpf instead.
syscallLsfStmtUse golang.org/x/net/bpf instead.
syscallParseRoutingMessageUse golang.org/x/net/route instead.
syscallParseRoutingSockaddrUse golang.org/x/net/route instead.
syscallRouteMessageUse golang.org/x/net/route instead.
syscallRouteRIBUse golang.org/x/net/route instead.
syscallRoutingMessageUse golang.org/x/net/route instead.
syscallSetBpfUse golang.org/x/net/bpf instead.
syscallSetBpfBuflenUse golang.org/x/net/bpf instead.
syscallSetBpfDatalinkUse golang.org/x/net/bpf instead.
syscallSetBpfHeadercmplUse golang.org/x/net/bpf instead.
syscallSetBpfImmediateUse golang.org/x/net/bpf instead.
syscallSetBpfInterfaceUse golang.org/x/net/bpf instead.
syscallSetBpfPromiscUse golang.org/x/net/bpf instead.
syscallSetBpfTimeoutUse golang.org/x/net/bpf instead.
syscallSetLsfPromiscUse golang.org/x/net/bpf instead.

go1.6


Go 版本頁
套件符號官方說明
compress/flateReadErrorNo longer returned.
compress/flateWriteErrorNo longer returned.
net/httpTransport.CancelRequestUse [Request.WithContext] to create a request with a cancelable context instead. CancelRequest cannot cancel HTTP/2 requests. This may become a no-op in a future release of Go.

go1.5


Go 版本頁
套件符號官方說明
archive/zipFileHeader.CompressedSizeUse CompressedSize64 instead.
archive/zipFileHeader.UncompressedSizeUse UncompressedSize64 instead.
go/docPackage.BugsFor backward compatibility Bugs is still populated, but all new code should use Notes instead.
image/jpegReaderReader is not used by the [image/jpeg] package and should not be used by others. It is kept for compatibility.
syscallFormatMessageUse FormatMessage from golang.org/x/sys/windows instead.
syscallStringBytePtrUse [BytePtrFromString] instead.
syscallStringByteSliceUse ByteSliceFromString instead.
syscallStringSlicePtrUse [SlicePtrFromStrings] instead.
syscallStringToUTF16Use [UTF16FromString] instead.
syscallStringToUTF16PtrUse [UTF16PtrFromString] instead.

資料來源